.net框架中的表达名称4

时间:2015-07-07 07:06:41

标签: c# c#-6.0 nameof

" nameof"表达式是在Visual Studio 2015和c#6中引入的

nameof (C# and Visual Basic Reference)

如何在旧版本中使用它或编写类似的方法,如.net framework 4。

5 个答案:

答案 0 :(得分:26)

如果你在C#6之前谈论C#的等价物,那么这将使得属性的工作完成(以一种黑客的方式)。它可以扩展到包括字段,方法等。

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

刚刚快速推特,所以还有很多需要改进的地方,但你这样使用它:

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

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

结果包含'myProp'

<强>更新

更全面(虽然还不是那么漂亮)

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

答案 1 :(得分:4)

nameOf - 在Compiletime处获得解析 - 如果您反编译,您将看到编译器只是将类名(没有命名空间(!))转换为常量字符串。 所以要注意!

如果您想获得一个classe的名称,请使用typeof()GetType()来获取Runtime的特定(可能派生)类型,并阅读
.Name - .net中的属性&lt; C#6。

MSDN

了解详情

答案 2 :(得分:2)

据我所知,有三种选择不必使用魔术字符串

  1. nameof ,需要Visual Studio 2015(但可以编译为其他版本的.net框架)

    nameof(this.Property)
    
  2. 使用一个方法,该方法接受一个表达式并返回此帖子中的属性名称&#34; Get string name of property using reflection&#34;

    var propertyName = GetPropertyName(  
        () => myObject.AProperty); // returns "AProperty"
    
  3. CallerMemberNameAttribute - (仅在.net framework 4.5中提供,因为原始帖子说的旧版本,如.net framework 4.0,我猜包括4.5)这个方法的缺点是它只在你需要时才有用您正在操作的当前方法的字符串表示。

    public string IsChecked  {
       set{
           Console.WriteLine(GetCurrentMemberName()); // prints "IsChecked"
       }
    }
    
    string GetCurrentMemberName([CallerMemberName] string memberName = "")
    {
         return memberName;
    }
    

答案 3 :(得分:1)

nameof运算符返回您传递的变量的字符串表示形式,因此nameof(var1)将返回&#34; var1&#34;,它有助于避免代码,我们必须将变量名称特定为字符串,如参数异常。

在以前的版本中,您可以使用反射或表达式树来实现类似的效果。

答案 4 :(得分:0)

@Rob,非常感谢,但是静态成员访问也可以用于非静态类成员。

(\d+)

好消息是Class不会被实例化。访问域层DTO很有用。