C# 如何从方法符号获取MethodInfo
是否可以从方法符号获取MethodInfo对象 因此,以同样的方式:C# 如何从方法符号获取MethodInfo,c#,.net,reflection,C#,.net,Reflection,是否可以从方法符号获取MethodInfo对象 因此,以同样的方式: typeof(SomeClassSymbol) // this gets you a Type object 以下是我想做的: public class Meatwad { MethodInfo method; public Meatwad() { method = ReflectionThingy.GetMethodInfo(SomeMethod); } publ
typeof(SomeClassSymbol) // this gets you a Type object
以下是我想做的:
public class Meatwad
{
MethodInfo method;
public Meatwad()
{
method = ReflectionThingy.GetMethodInfo(SomeMethod);
}
public void SomeMethod() { }
}
如何实现ReflectionSingy.GetMethodInfo?考虑到这甚至是可能的,那么重载方法呢?这在C中是不可能的。但你可以自己建造:
static MemberInfo MemberInfoCore(Expression body, ParameterExpression param)
{
if (body.NodeType == ExpressionType.MemberAccess)
{
var bodyMemberAccess = (MemberExpression)body;
return bodyMemberAccess.Member;
}
else if (body.NodeType == ExpressionType.Call)
{
var bodyMemberAccess = (MethodCallExpression)body;
return bodyMemberAccess.Method;
}
else throw new NotSupportedException();
}
public static MemberInfo MemberInfo<T1>(Expression<Func<T1>> memberSelectionExpression)
{
if (memberSelectionExpression == null) throw new ArgumentNullException("memberSelectionExpression");
return MemberInfoCore(memberSelectionExpression.Body, null/*param*/);
}
这将为您提供编译时安全性。不过,性能不会很好。学员在其任务中包含所需的
MethodInfo
。因此,您的助手方法可以简单到:
MethodInfo GetMethodInfo(Delegate d)
{
return d.Method;
}
不能直接从方法组转换为委托
。但是你可以用石膏来做。例如:
GetMethodInfo((Action)Console.WriteLine)
请注意,如果您试图将其与usr的解决方案之类的东西混合使用,这将不起作用。比如说
GetMethodInfo((Action)(() => Console.WriteLine()))
将为生成的匿名方法返回
MethodInfo
,而不是Console.WriteLine()
为什么方法中有一个从未使用过的参数?我从一个有200个LOC的助手类中复制了这个。我只是想说明一下要点。请将其视为伪代码;-)不过,这个想法会完全奏效。@usr当性能出现问题时,使用它初始化静态只读对象,而不是每次调用函数,很容易解决问题。我觉得有点相关:Eric Lippert的“In-Foof We Trust:a Dialog”链接在上面断开了。到目前为止,我最喜欢这个,但有趣的是,您可以只使用方法符号构造一个动作,并从动作的method属性获取MethodInfo。这就是我最终要学的。如果我有时间,我将反编译操作,看看发生了什么。
GetMethodInfo((Action)(() => Console.WriteLine()))