加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:22:12 所属栏目:百科 来源:网络整理
导读:它们可以如下使用: FieldInfo field = fieldof(string.Empty);MethodInfo method1 = methodof(int.ToString);MethodInfo method2 = methodof(int.ToString(IFormatProvider)); fieldof可以编译为IL,如下: ldtoken fieldcall FieldInfo.GetFieldFromHandle
它们可以如下使用:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读