开发者

How to get attributes value

I have this code:

[MyAttribute(CustomAttribute="Value")]
class MyClass
开发者_如何转开发{
    // some code
}


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

How to get value of CustomAttribute for instance a?


Along the lines of:

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

Can't understand what you mean by "without using foreach", except that GetCustomAttributes always returns an array of them (to account for having multiple attributes). If you know there can only be one, then just use the first one.

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


There is a good sample here:

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

To do this without a foreach you would have to assume there are no other attributes being applied to the type, and index the first attribute directly.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜