Instead of
if (somecondition == 1)
{
int result = new myDelegate(MyClass.myMethod1);
}
else
{
int result = new myDelegate(MyClass.myMethod2);
}
Is it possible to do something like this
int result = new myDelegate("MyClass.myMethod" + i.ToString()); }
myDelegate dlg = (myDelegate)Delegate.CreateDelegate(typeof(myDelegate), this, "myMethod" + i);
You can do this via Reflection (but I don't necessarily recommend it):
string MethodName = "myMethod" + i.ToString();
Type type = MyClass.GetType();
MethodInfo methodInfo = type.GetMethod(MethodName);
int result = (int) methodInfo.Invoke(MyClass, null);
Yes, you can dynamically invoke methods using reflection. Small sample:
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
Well, needed just too long for this, but after i've done this, I'm gonna post this too ;-)
BEWARE: Reflektion is far far slower than using delegates!
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[] {});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.