![](/img/trans.png)
[英]How Can I Get Current Method's Name And Its Arguments(name and value) in C#
[英]How can I get a method handler by its name? (c#)
請查看下面的代碼以了解我的問題:
public class MyClass
{
public delegate object MyDelegate(object value);
public MyDelegate GetMethodByName(string methodName)
{
// What have to be here?
}
public object Method1(object value)
{
// some code here
}
public object Method2(object value)
{
// some code here
}
public object Method3(object value)
{
// some code here
}
}
在某個地方:
var obj = new MyClass();
MyDelegate del = obj.GetMethodByName("Method1");
var result = del(someobject);
那么如何通過名稱獲取方法處理程序呢? (C#)
var obj = new MyClass();
MyDelegate del = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), obj.GetType().GetMethod("Method1"));
var result = del(someobject);
public class MyClass
{
public delegate object MyDelegate(object value);
public MyDelegate GetMethodByName(string methodName)
{
return (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), this.GetType().GetMethod(methodName));
}
public object Method1(object value)
{
throw new NotImplementedException();
}
public object Method2(object value)
{
throw new NotImplementedException();
}
public object Method3(object value)
{
throw new NotImplementedException();
}
}
我認為你在這里想要實現的是C#中的動態方法調用。 說實話,有很多方法可以做到這一點。 大多數人會使用反射來做這種事情,但我會稍微重新設計代碼。 這是一個可能有用的鏈接
http://www.csharphelp.com/2006/05/dynamic-method-invocation-in-c-using-reflection/
您似乎需要動態構造一個委托給由反射檢索的方法。 為此,您可以使用CreateDelegate
方法,如下所示。
public MyDelegate GetMethodByName(string methodName)
{
MethodInfo method = GetType().GetMethod(methodName); // use BindingFlags if method is static/non-public.
return (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), method);
}
當然,您需要確保MyDelegate
的簽名與給定方法的簽名匹配。
public class MyClass
{
public delegate object MyDelegate(object value);
MyDelegate del1, del2, del3;
public MyClass()
{
del1 = Method1;
del2 = Method2;
del3 = Method3;
// remaining Ctr code here
}
public MyDelegate GetMethodByName(string methodName)
{
if (methodName.Equals("Method1"))
return del1;
if (methodName.Equals("Method2"))
return del2;
if (methodName.Equals("Method3"))
return del3;
return null;
}
public object Method1(object value)
{
// some code here
return null;
}
public object Method2(object value)
{
// some code here
return null;
}
public object Method3(object value)
{
// some code here
return null;
}
}
如果要查找的方法列表僅限於靜態定義的方法,並且沒有重載方法,則此解決方案可以在不使用反射的情況下工作。 但是,如果您希望解決方案是通用的,或者使用重載方法,那么您將采用其他帖子使用反射提到的方式。
使用反射,您可以像這樣獲得對MethodInfo實例的引用。
MethodInfo[] methodInfos = typeof(MyClass).GetMethods(BindingFlags.Public |
BindingFlags.Static);
MethodInfo method1 = methodInfos.SingleOrDefault(m => m.Name == "method1");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.