3

Considering Myatt attribute and MyObj class, it is somehow strange that ObjName property is known in scope of Myatt attribute. Isn't it?

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

Update :

Sorry, I'm wondering why the first case is not possible and the second is possible.

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

I get it now. Thanks.

4

2 回答 2

8

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

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

[DebuggerDisplay("={" + nameof(GetString) + "()}")]  
class C {  
    string GetString() { }  
}  
于 2017-05-08T14:54:04.907 回答
1

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

于 2017-05-08T14:52:53.863 回答