【问题标题】:nameof in attribute [closed]属性中的nameof [关闭]
【发布时间】:2017-10-06 15:18:56
【问题描述】:

考虑到Myatt 属性和MyObj 类,奇怪的是ObjName 属性在Myatt 属性的范围内是已知的。不是吗?

[AttributeUsage(AttributeTargets.Property)]
public class MyAtt : Attribute
{
    public MyAtt(string name)
    {
        this.Name = name;
    }

    public string Name
    {
        get; set;
    }
}

public class MyObj
{
    [MyAtt(nameof(ObjName))] //Can access to ObjName?!
    public int ObjID
    {
        get;
        set;
    }

    public string ObjName
    {
        get;
        set;
    }
}

更新:

对不起,我想知道为什么第一种情况是不可能的,而第二种情况是可能的。

1. [MyAtt(nameof(this.ObjName))] 
2. [MyAtt(nameof(ObjName))] 

我现在明白了。谢谢。

【问题讨论】:

  • 你有什么问题?如果我们也觉得您的代码有效吗?

标签: c# nameof .net-attributes


【解决方案1】:

那里支持它很好,不是吗?所以不,这并不奇怪。

Documentation 提到了一个 Attribute 示例作为关键用例:

[DebuggerDisplay("={" + nameof(GetString) + "()}")]  
class C {  
    string GetString() { }  
}  

【讨论】:

    【解决方案2】:

    如果您将nameof(...) 视为语法糖,那么这并不奇怪 - 您的属性接受一个字符串,编译器会在编译时计算出该字符串(考虑到由于重构而导致的任何重命名)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      相关资源
      最近更新 更多