.net Framework 4中的表达式名称 [英] nameof expression in .net framework 4

查看:106
本文介绍了.net Framework 4中的表达式名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Visual Studio 2015和c#6中引入了表达式

"nameof" expression is introduced in Visual Studio 2015 and c# 6

名称(C#和Visual Basic参考)

如何在较旧的版本(如.net Framework 4)中使用它或编写类似的方法?

How can u use it or write a similar method in older versions like .net framework 4.

推荐答案

如果您要在C#6之前谈论C#的等效项,那么这将(以hacky的方式)完成属性的工作.它可能可以扩展为包括字段,方法等.

If you're talking about an equivalent for C# before C#6, this will get the job done (in a hacky way) for properties. It can probably be expanded upon to include fields, methods, etc.

public static class TestExtension
{
    public static String nameof<T, TT>(this T obj, Expression<Func<T, TT>> propertyAccessor)
    {
        if (propertyAccessor.Body.NodeType == ExpressionType.MemberAccess)
        {
            var memberExpression = propertyAccessor.Body as MemberExpression;
            if (memberExpression == null)
                return null;
            return memberExpression.Member.Name;
        }
        return null;
    }
}

只是快速地进行了说明,因此有很多地方需要改进,但是您可以这样使用它:

Just whipped this up quickly, so there's a lot to be improved, but you use it like this:

public class myClass
{
    public string myProp { get; set; }
}

var a = new myClass();
var result = a.nameof(b => b.myProp);

结果包含"myProp"

Result contains 'myProp'

更新:

更全面(尽管仍然不那么漂亮)

More comprehensive (though still not that pretty)

public static class TestExtension
{
    public static String nameof<T, TT>(this Expression<Func<T, TT>> accessor)
    {
        return nameof(accessor.Body);
    }

    public static String nameof<T>(this Expression<Func<T>> accessor)
    {
        return nameof(accessor.Body);
    }

    public static String nameof<T, TT>(this T obj, Expression<Func<T, TT>> propertyAccessor)
    {
        return nameof(propertyAccessor.Body);
    }

    private static String nameof(Expression expression)
    {
        if (expression.NodeType == ExpressionType.MemberAccess)
        {
            var memberExpression = expression as MemberExpression;
            if (memberExpression == null)
                return null;
            return memberExpression.Member.Name;
        }
        return null;
    }
}

访问静态属性/字段:

TestExtension.nameof(() => myClass.MyOtherField)

访问函数中的参数:

void func (int a) {
    TestExtension.nameof(() => a);
}

这篇关于.net Framework 4中的表达式名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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