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)));
}
call RuntimeHelpers.get_OffsetToStringData
withldc.i4 <int32 offset>
inline (before native code generation). – PedigoINotifyPropertyChanged
. – InquisitionistArgumentException
– PentatomicArgumentException
constructor overload that takes two strings uses the name of the offending parameter the same way that aDependencyProperty
is registered. This demonstrates that the need offieldof
operator would be of significant use to a broader range of developers besides simply those working on WPF applications. – Pentatomic