2010-08-02 152 views
7

我有这样的代码:如何获得属性值

[MyAttribute(CustomAttribute="Value")] 
class MyClass 
{ 
    // some code 
} 


Main() 
{ 
    MyClass a = new MyClass(); 
} 

如何获得CustomAttribute的值,例如一个?

回答

3

线沿线的:

MyAttribute [] myAttributes 
    = (MyAttribute [])a.GetType().GetCustomAttributes(typeof(MyAttribute),true); 

不能明白你的意思“而无需使用的foreach”,除了GetCustomAttributes总是返回他们的数组(考虑具有多个属性) 。如果你知道只能有一个,那就用第一个。

MyAttribute theAttrib = myAttributes[0]; 
Console.WriteLine(theAttrib.CustomAttribute); 
+0

“不能明白你的意思‘而无需使用的foreach’” - > 我发现使用的foreach读取所有属性值 – Dusan 2010-08-02 14:11:57

+0

一些不好的例子是,但坏的例子是 - 例子 - 你应该接受他们所提供的知识,并且如何使用它。 – Jamiec 2010-08-02 14:36:57

1
var attribs = (MyAttributeAttribute[]) typeof(MyClass).GetCustomAttributes(
    typeof(MyAttributeAttribute), 
    true); 

Console.WriteLine(attribs[0].CustomAttribute); // prints 'Value'