簡體   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