为什么 C# 中没有 `fieldof` 或 `methodof` 运算符? [英] Why is there not a `fieldof` or `methodof` operator in C#?

查看:18
本文介绍了为什么 C# 中没有 `fieldof` 或 `methodof` 运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它们可以如下使用:

FieldInfo field = fieldof(string.Empty);
MethodInfo method1 = methodof(int.ToString);
MethodInfo method2 = methodof(int.ToString(IFormatProvider));

fieldof 可以编译为 IL 为:

fieldof could be compiled to IL as:

ldtoken <field>
call FieldInfo.GetFieldFromHandle

methodof 可以编译为 IL 为:

methodof could be compiled to IL as:

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# 设计团队中)对这个主题有一个很好的概述/讨论 此处.引用:

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.

这篇关于为什么 C# 中没有 `fieldof` 或 `methodof` 运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆