繁体   English   中英

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

[英]Is it possible to call a C# delegate by method name

代替

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

是否可以做这样的事情

int result = new myDelegate("MyClass.myMethod" + i.ToString()); }
myDelegate dlg = (myDelegate)Delegate.CreateDelegate(typeof(myDelegate), this, "myMethod" + i);

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

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

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

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 

好吧,这需要太长的时间,但是在完成此操作后,我也将发布此内容;-)

注意:反射要比使用委托慢得多!

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[] {});
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM