如何获得属性值

时间:2010-08-02 13:54:03

标签: c# attributes

我有这段代码:

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


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

如何获取CustomAttribute的值,例如a?

3 个答案:

答案 0 :(得分:3)

这里有一个很好的样本:

http://msdn.microsoft.com/en-us/library/z919e8tw.aspx

要在没有foreach的情况下执行此操作,您必须假设没有其他属性应用于该类型,并直接索引第一个属性。

答案 1 :(得分:3)

遵循:

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

无法理解“不使用foreach”的含义,除了GetCustomAttributes总是返回它们的数组(以考虑具有多个属性)。如果你知道只有一个,那就用第一个。

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

答案 2 :(得分:1)

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

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