They could be used as follows:
FieldInfo field = fieldof(string.Empty);
MethodInfo method1 = methodof(int.ToString);
MethodInfo method2 = methodof(int.ToString(IFormatProvider));
fieldof
could be compiled to IL as:
ldtoken <field>
call FieldInfo.GetFieldFromHandle
methodof
could be compiled to IL as:
ldtoken <method>
call MethodBase.GetMethodFromHandle
Whenever the typeof
operator is used, you get perfect Find All References results. Unfortunately, as soon as you go to fields or methods, you end up with nasty hacks. I think you could do the following... or you can go back to getting a field by name.
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 = methodof(() => default(string).ToString());
MethodInfo method2 = methodof(() => default(string).ToString(default(IFormatProvider)));
MethodInfo method3 = methodof(() => default(List<int>).Add(default(int)));
}
this is a generic type version, that can use F2 to rename and not need modify existed code in the example, the method name is GetPKValue
You can actually avoid using both reflection and lambdas (.NET Framework 2.0). Consider the following class:
and it's usage:
Eric Lippert (on the C# design team) has an excellent overview/discussion on this topic here. To quote:
@280Z28 - We were just sitting down to figure out how to do this when I found your question & code. We needed a PropertyOf method so I added it. Here it is in case anybody else needs it. Thx for the great question.