首页 新闻 会员 周边

获取类型中所有的具有指定特性类型的属性

0
悬赏园豆:10 [已解决问题] 解决于 2010-06-05 13:48

C# 获取类型中所有的具有指定特性类型的属性。

示例:

class MyClass
{
[MyCustom]
  
public int Property1 {get;set;}

[MyCustom(Name
="abc")]]
public int Property2 {get;set;}
}

获取此类中所有具有"MyCustom"特性的属性

TypeDescriptor.GetProperties 这个方法我试了不行,此方法中有个特性数组的参数,只能传实例,而不能传类型。如果传一个"Name"为空的"MyCustom"就只能匹配到第一个属性。

luotong的主页 luotong | 初学一级 | 园豆:4
提问于:2010-05-25 11:29
< >
分享
最佳答案
0

以下是c#4.0中的实现,如果你用的是低版本,修改var就可以了

代码
1
2  class MyClass
3 { public static void Main(string[] args) {
4 var t = typeof(Abc);
5 var properties = t.GetProperties();
6 var result = new ArrayList();
7 foreach (var property in properties)
8 {
9 var attr = Attribute.GetCustomAttribute(property, typeof(DefaultValueAttribute));
10 if (attr != null) {
11 result.Add(property);
12 }
13 }
14
15 Console.WriteLine("result's count = " + result.Count);
16 Console.ReadLine();
17 }
18
19 }
20
21 public class Abc
22 {
23 public int ID { get; set; }
24
25 [DefaultValue("yukaizhao")]
26 public string Name { get; set; }
27
28 public string Url { get; set; }
29 }
收获园豆:10
玉开 | 大侠五级 |园豆:8822 | 2010-05-25 12:53
看来只能循环了
luotong | 园豆:4 (初学一级) | 2010-06-05 13:49
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册