所以我有以下内容:
public class Singleton
{
private Singleton(){}
public static readonly Singleton instance = new Singleton();
public string DoSomething(){ ... }
public string DoSomethingElse(){ ... }
}
使用反射如何调用DoSomething方法?
我问的原因是因为我将方法名称存储在XML中并动态创建UI。例如,我正在动态创建一个按钮,并告诉它在单击按钮时通过反射调用的方法。在某些情况下,它将是DoSomething,或者在其他情况下,它将是DoSomethingElse。
答案 0 :(得分:11)
未经测试,但应该有效......
string methodName = "DoSomething"; // e.g. read from XML
MethodInfo method = typeof(Singleton).GetMethod(methodName);
FieldInfo field = typeof(Singleton).GetField("instance",
BindingFlags.Static | BindingFlags.Public);
object instance = field.GetValue(null);
method.Invoke(instance, Type.EmptyTypes);
答案 1 :(得分:4)
干得好。谢谢。
对于无法引用远程程序集的情况,这里采用相同的方法稍加修改。我们只需要知道基本的东西,比如类的全名(即namespace.classname和远程程序集的路径)。
static void Main(string[] args)
{
Assembly asm = null;
string assemblyPath = @"C:\works\...\StaticMembers.dll"
string classFullname = "StaticMembers.MySingleton";
string doSomethingMethodName = "DoSomething";
string doSomethingElseMethodName = "DoSomethingElse";
asm = Assembly.LoadFrom(assemblyPath);
if (asm == null)
throw new FileNotFoundException();
Type[] types = asm.GetTypes();
Type theSingletonType = null;
foreach(Type ty in types)
{
if (ty.FullName.Equals(classFullname))
{
theSingletonType = ty;
break;
}
}
if (theSingletonType == null)
{
Console.WriteLine("Type was not found!");
return;
}
MethodInfo doSomethingMethodInfo =
theSingletonType.GetMethod(doSomethingMethodName );
FieldInfo field = theSingletonType.GetField("instance",
BindingFlags.Static | BindingFlags.Public);
object instance = field.GetValue(null);
string msg = (string)doSomethingMethodInfo.Invoke(instance, Type.EmptyTypes);
Console.WriteLine(msg);
MethodInfo somethingElse = theSingletonType.GetMethod(
doSomethingElseMethodName );
msg = (string)doSomethingElse.Invoke(instance, Type.EmptyTypes);
Console.WriteLine(msg);}