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))); }
You can actually avoid using both reflection and lambdas (.NET Framework 2.0). Consider the following class:
public class methodof<T> { private MethodInfo method; public methodof(T func) { Delegate del = (Delegate)(object)func; this.method = del.Method; } public static implicit operator methodof<T>(T methodof) { return new methodof<T>(methodof); } public static implicit operator MethodInfo(methodof<T> methodof) { return methodof.method; } }
and it's usage:
MethodInfo writeln = (methodof<Action>)Console.WriteLine; MethodInfo parse = (methodof<Func<string, int>>)int.Parse;
Eric Lippert (on the C# design team) has an excellent overview/discussion on this topic here. To quote:
It’s an awesome feature that pretty much everyone involved in the design process wishes we could do, but there are good practical reasons why we choose not to. If there comes a day when designing it and implementing it is the best way we could spend our limited budget, we’ll do it. Until then, use Reflection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With