怎么得到一个Attribute的名字
如何得到一个Attribute的名字?
例如,我创建一个简单的控制台程序,添加了3个属性,S1,S2,S3,给S1和S3加上一个CategoryAttribute。
然后我希望用函数LoopProp来遍历所有的属性,找出其中含有"Category"这个Attribute的属性,并打印出来,代码如下:
程序的输出是什么都不打印。我调试程序,发现Attribute这个类型的成员很少,并没有一个形如Name或者Type的成员。
我的程序应该如何改动? 如果我要打印出含有Category这个Attribute,并且其值为"YourString"的属性,又该如何改代码?
谢谢。
------解决思路----------------------
http://msdn.microsoft.com/zh-cn/library/system.attribute(VS.80).aspx 看看介绍
------解决思路----------------------
反射得到PropertyInfo,然后调用Attribute.GetCustomAttributes
例如,我创建一个简单的控制台程序,添加了3个属性,S1,S2,S3,给S1和S3加上一个CategoryAttribute。
然后我希望用函数LoopProp来遍历所有的属性,找出其中含有"Category"这个Attribute的属性,并打印出来,代码如下:
class Program
{
[Category("MyString")]
public string S1 { get; set; }
public string S2 { get; set; }
[Category("YourString")]
public string S3 { get; set; }
public void LoopProp()
{
var props = TypeDescriptor.GetProperties(this, true);
foreach (PropertyDescriptor prop in props)
{
var attr = prop.Attributes;
foreach (Attribute a in attr)
{
if(a.ToString().Equals("Category"))
Console.WriteLine(prop.Name);
}
}
}
static void Main(string[] args)
{
new Program().LoopProp();
}
}
程序的输出是什么都不打印。我调试程序,发现Attribute这个类型的成员很少,并没有一个形如Name或者Type的成员。
我的程序应该如何改动? 如果我要打印出含有Category这个Attribute,并且其值为"YourString"的属性,又该如何改代码?
谢谢。
------解决思路----------------------
http://msdn.microsoft.com/zh-cn/library/system.attribute(VS.80).aspx 看看介绍
------解决思路----------------------
反射得到PropertyInfo,然后调用Attribute.GetCustomAttributes