【发布时间】:2012-06-06 22:57:34
【问题描述】:
我需要获取在 Action 委托中调用的方法的 MethodInfo 以检查在 Action 中调用的方法是否具有 MyCustomAttibute
public void Foo( Action action )
{
if(Attribute.GetCustomAttributes(action.Method, typeof(MyCustomAttribute)).Count() == 0)
{
throw new ArgumentException("Invalid action");
}
}
Foo 方法应该可以如下调用:
Foo(() =>
{
instanceOfFooClass.Method1().Method2();
});
在 Foo 方法中,我想确保 Method1 和 Method2 具有 MyCustomAttribute。但是 action.Method 给了我 MethodInfo,这是委托的操作,在使用 lambda 表达式时发生。有什么方法可以获取 Method1 和 Method2 MethodInfo 吗?
【问题讨论】:
-
很好的问题。不是很容易,AFAIK。您可以可能使用
Expression<Action>轻松完成它,但是您不能直接执行它 -
我同意你必须为此使用表达式树。我不知道这会对性能造成多大影响。
-
如果不直接,那怎么执行呢?
-
另外一个问题是带有语句体的lambda表达式不能用作Expression
。