2010-05-09 193 views
6
[MyAttribute()] 
public string Name { get; set; } 

MyAttribute我需要知道关联属性的名称,这有可能吗?.NET:获取属性名称属性

编辑:

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

+0

你能详细说明为什么你需要它,你会用它来做什么? – 2010-05-09 11:07:54

+0

你需要说明 – 2010-05-09 11:12:33

回答

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 
    } 
} 
+0

嗯,可能是我从对立端看问题比我应该。 – Feryt 2010-05-09 11:17:07

+0

是的,你从一个类型开始,然后获取属性并最终读取应用于给定属性的自定义属性。 – 2010-05-09 11:19:10

0

您可以使用PostSharp方面来完成这项工作。我有一个类似的question回来,这几乎是一回事。您可以在答案中看到关于您可能遇到的一些含义的更多信息的评论。