当前位置 : 主页 > 编程语言 > c语言 >

为什么C#中没有`fieldof`或`methodof`运算符?

来源:互联网 收集:自由互联 发布时间:2021-06-25
它们可以如下使用: FieldInfo field = fieldof(string.Empty);MethodInfo method1 = methodof(int.ToString);MethodInfo method2 = methodof(int.ToString(IFormatProvider)); fieldof可以编译为IL,如下: ldtoken fieldcall FieldInfo.Get
它们可以如下使用:

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运算符时,您都可以获得完美的查找所有引用结果.不幸的是,一旦你去了田野或方法,你最终会遇到令人讨厌的黑客攻击.我想你可以做以下事情……或者你可以回去按名字命名.

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.引用:

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.

网友评论