如何获得属性值
问题描述:
我有这样的代码:如何获得属性值
[MyAttribute(CustomAttribute="Value")]
class MyClass
{
// some code
}
Main()
{
MyClass a = new MyClass();
}
如何获得CustomAttribute的值,例如一个?
答
线沿线的:
MyAttribute [] myAttributes
= (MyAttribute [])a.GetType().GetCustomAttributes(typeof(MyAttribute),true);
不能明白你的意思“而无需使用的foreach”,除了GetCustomAttributes总是返回他们的数组(考虑具有多个属性) 。如果你知道只能有一个,那就用第一个。
MyAttribute theAttrib = myAttributes[0];
Console.WriteLine(theAttrib.CustomAttribute);
答
有一个很好的样本这里:第一属性直接
http://msdn.microsoft.com/en-us/library/z919e8tw.aspx
要做到这一点没有一个foreach你必须假定有被应用到该类型没有其他属性和索引。
答
var attribs = (MyAttributeAttribute[]) typeof(MyClass).GetCustomAttributes(
typeof(MyAttributeAttribute),
true);
Console.WriteLine(attribs[0].CustomAttribute); // prints 'Value'
“不能明白你的意思‘而无需使用的foreach’” - > 我发现使用的foreach读取所有属性值 – Dusan 2010-08-02 14:11:57
一些不好的例子是,但坏的例子是 - 例子 - 你应该接受他们所提供的知识,并且如何使用它。 – Jamiec 2010-08-02 14:36:57