是否可以通过方法名称调用C#委托

时间:2009-09-28 20:05:18

标签: c#

而不是

if (somecondition == 1) 
{
    int result = new myDelegate(MyClass.myMethod1); 
}
else 
{
    int result = new myDelegate(MyClass.myMethod2);
}

是否可以做这样的事情

int result = new myDelegate("MyClass.myMethod" + i.ToString()); }

4 个答案:

答案 0 :(得分:6)

myDelegate dlg = (myDelegate)Delegate.CreateDelegate(typeof(myDelegate), this, "myMethod" + i);

答案 1 :(得分:5)

你可以通过反思来做到这一点(但我不一定推荐):

string MethodName = "myMethod" + i.ToString();
Type type = MyClass.GetType();
MethodInfo methodInfo = type.GetMethod(MethodName);
int result = (int) methodInfo.Invoke(MyClass, null);

答案 2 :(得分:1)

是的,您可以使用反射动态调用方法。小样本:

public class MyClass {
    public delegate string MyDelegate();
    public string MyMethod1() {
        return "Hello";
    }
    public string MyMethod2() {
        return "Bye";
    }
}

int i;
MyClass myInstance = new MyClass();
MethodInfo method = typeof(MyClass).GetMethod("MyMethod" + i.ToString());
Delegate del = Delegate.CreateDelegate(typeof(MyClass.MyDelegate), myInstance, method);
Console.WriteLine(del()); // prints "Hello" or "Bye" contingent on value of i 

答案 3 :(得分:1)

嗯,这需要太长时间了,但是在我这样做之后,我也会发布这个; - )

当心:Reflektion远比使用代表慢得多!

Type t = typeof(MainClass);
MethodInfo mi = null;
int i = 2;
if (i==1) 
{
    mi = t.GetMethod("myMethod" + i.ToString());
}
else 
{
    mi = t.GetMethod("myMethod" + i.ToString());
}   

if(mi != null)
{
    mi.Invoke(new object(), new object[] {});
}
相关问题