它们可以如下使用:
FieldInfo field = fieldof(string.Empty);
MethodInfo method1 = methodof(int.ToString);
MethodInfo method2 = methodof(int.ToString(IFormatProvider));
Run Code Online (Sandbox Code Playgroud)
fieldof 可以编译为IL为:
ldtoken <field>
call FieldInfo.GetFieldFromHandle
Run Code Online (Sandbox Code Playgroud)
methodof 可以编译为IL为:
ldtoken <method>
call MethodBase.GetMethodFromHandle
Run Code Online (Sandbox Code Playgroud)
无论何时使用typeof运算符,您都可以获得完美的查找所有引用结果.不幸的是,一旦你去了田野或方法,你最终会遇到令人讨厌的黑客攻击.我想你可以做以下事情......或者你可以回去按名字命名.
public static FieldInfo fieldof<T>(Expression<Func<T>> expression)
{
MemberExpression body = (MemberExpression)expression.Body;
return (FieldInfo)body.Member;
}
public static MethodInfo methodof<T>(Expression<Func<T>> expression)
{
MethodCallExpression body = (MethodCallExpression)expression.Body;
return body.Method;
}
public static MethodInfo methodof(Expression<Action> expression)
{
MethodCallExpression body = (MethodCallExpression)expression.Body;
return body.Method;
}
public static void Test()
{
FieldInfo field = fieldof(() => string.Empty);
MethodInfo method1 …Run Code Online (Sandbox Code Playgroud) 我想编写一个函数,它将函数f作为参数,并返回与f关联的System.Reflection.MethodInfo.
我不太确定它是否可行.
我知道我可以有一个属性,但这比我想去的工作更多......而且不够通用.
我想做点什么
class Whotsit
{
private string testProp = "thingy";
public string TestProp
{
get { return testProp; }
set { testProp = value; }
}
}
...
Whotsit whotsit = new Whotsit();
string value = GetName(whotsit.TestProp); //precise syntax up for grabs..
Run Code Online (Sandbox Code Playgroud)
在哪里我期望价值等于"TestProp"
但我不能为我的生活找到正确的反射方法来编写GetName方法...
编辑:我为什么要这样做?我有一个类来存储从'name','value'表中读取的设置.这由基于反射的通用方法填充.我很想反写...
/// <summary>
/// Populates an object from a datatable where the rows have columns called NameField and ValueField.
/// If the property with the 'name' exists, and is not read-only, it is populated from the …Run Code Online (Sandbox Code Playgroud)