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

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

概述它们可以如下使用: FieldInfo field = fieldof(string.Empty);MethodInfo method1 = methodof(int.ToString);MethodInfo method2 = methodof(int.ToString(IFormatProvider)); fieldof可以编译为IL,如下: ldtoken <field>call Fi 它们可以如下使用:

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.

总结

以上是内存溢出为你收集整理的为什么C#中没有`fieldof`或`methodof`运算符?全部内容,希望文章能够帮你解决为什么C#中没有`fieldof`或`methodof`运算符?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1214505.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存