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

标签 c# reflection

<分区>

它们可以按如下方式使用:

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)));
}

最佳答案

您实际上可以避免同时使用反射和 lambdas (.NET Framework 2.0)。考虑以下类:

public class methodof<T>
{
    private MethodInfo method;

    public methodof(T func)
    {
        Delegate del = (Delegate)(object)func;
        this.method = del.Method;
    }

    public static implicit operator methodof<T>(T methodof)
    {
        return new methodof<T>(methodof);
    }

    public static implicit operator MethodInfo(methodof<T> methodof)
    {
        return methodof.method;
    }
}

及其用法:

MethodInfo writeln = (methodof<Action>)Console.WriteLine;
MethodInfo parse = (methodof<Func<string, int>>)int.Parse;

关于c# - 为什么 C# 中没有 `fieldof` 或 `methodof` 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1213862/

相关文章:

c# - 通过字符串名称获取属性值

Java:如何在 Java 反射中为 constructor.newInstance() 使用非原始类型?

java - 使用无参数构造函数创建代理类

c# - 如何按值查找json token,然后删除token

c# - WPF WebBrowser-Control 不显示内容

c# - Selenium WebDriver 测试登录验证

arrays - 在golang中转储接口(interface)数组

java - 如何检查类的注释是否属于特定类别?

c# - Entity Framework 中的 "The data reader has more than one field"错误

c# - 获取一组矩形的轮廓