.NET:在属性中获取属性名称

时间:2010-05-09 11:04:18

标签: .net attributes

[MyAttribute()]
public string Name { get; set; }

MyAttribute我需要知道相关属性的名称,是否可能?

修改

我需要在文本格式中使用它。

2 个答案:

答案 0 :(得分:8)

不,这是不可能的。通常您会在给定的属性上使用reflection to read attributes,因此您已经知道该属性。例如:

var properties = typeof(SomeType).GetProperties();
foreach (var property in properties)
{
    var attributes = property.GetCustomAttributes(typeof(MyAttribute), true);
    if (attributes.Count > 0)
    {
        // look at property.Name here
    }
}

答案 1 :(得分:0)

您可以使用PostSharp方面来完成工作。我有一段相似的question,这几乎是一回事。您可以在答案上看到有关您可能遇到的一些影响的更多信息。

相关问题