为什么C#中没有`fieldof`或`methodof`运算符? [英] Why is there not a `fieldof` or `methodof` operator in C#?
问题描述
它们可以如下使用:
FieldInfo field = fieldof(string.Empty);
MethodInfo method1 = methodof(int.ToString);
MethodInfo method2 = methodof(int.ToString(IFormatProvider));
fieldof
可以编译为IL:
ldtoken <field>
call FieldInfo.GetFieldFromHandle
methodof
可以编译为IL:
ldtoken <method>
call MethodBase.GetMethodFromHandle
每当 typeof
运算符被使用,你得到完美的查找全部参考结果。不幸的是,一旦你去田野或方法,你最终会有恶意的黑客。我想你可以执行以下操作,或者你可以按名称返回一个字段。
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)));
}
推荐答案
Eric Lippert(在C#设计团队)对此主题有一个很好的概述/讨论 here 。引用:
Eric Lippert (on the C# design team) has an excellent overview/discussion on this topic here. To quote:
这是一个非常棒的功能,几乎所有参与设计过程的人都希望我们能做,但是有很好的实际原因我们选择不去。如果有一天设计它并实施它是我们可以花费我们有限预算的最好方法,我们会这样做。在此之前,请使用Reflection。
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.
这篇关于为什么C#中没有`fieldof`或`methodof`运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!