[英]How to get non-static MethodInfo using method name (not in string, not searching in class type)
Consider following code: 考虑以下代码:
public class Test
{
[System.AttributeUsage(System.AttributeTargets.Method)]
class MethodAttribute : System.Attribute
{
public MethodAttribute(System.Reflection.MethodInfo methodInfo)
{
}
}
public void Foo()
{
}
[Method(Test.Foo)] //< THIS IS THE IMPORTANT LINE
public void Boo()
{
}
}
I want to store MethodInfo instance of Foo in attribute of Boo, but problem is, that I cannot use Foo
nor Test.Foo
to get instance of MethodInfo
. 我想将Foo的MethodInfo实例存储在Boo的属性中,但是问题是,我无法使用
Foo
或Test.Foo
来获取MethodInfo
实例。 I can NOT use typeof(Test).GetMethod("Foo")
(not my decision). 我不能使用
typeof(Test).GetMethod("Foo")
(不是我的决定)。
Important information: 重要信息:
Absolutely unimportant information: 绝对不重要的信息:
typeof(Test).GetMethod("Foo")
: I'm not allowed. typeof(Test).GetMethod("Foo")
:我不允许。 It's not in my power to change this decision. use expression : 使用表达式:
static public class Metadata<T>
{
static public PropertyInfo Property<TProperty>(Expression<Func<T, TProperty>> property)
{
var expression = property.Body as MemberExpression;
return expression.Member as PropertyInfo;
}
}
var foo = Metadata<Test>.Property(test => test.Foo);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.