[英]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.