2017-08-01 340 views
0

我需要获取一个PropertyDescriptorCollection,其中包含用自定义属性装饰的所有属性。问题是,TypeDescriptor.GetProperties只能过滤所有属性的精确匹配,所以如果我想要获取所有属性,不管属性的属性如何设置,我将不得不覆盖过滤器数组中的所有可能性。获取PropertyDescriptorCollection自定义属性过滤属性

这里是我的attribue代码:

[AttributeUsage(AttributeTargets.Property)] 
class FirstAttribute : Attribute 
{ 
    public bool SomeFlag { get; set; } 
} 

而且具有装饰性的一类:

class Foo 
{ 
    [First] 
    public string SomeString { get; set; } 

    [First(SomeFlag = true)] 
    public int SomeInt { get; set; } 
} 

而且主:

static void Main(string[] args) 
{ 
    var firstPropCollection = TypeDescriptor.GetProperties(typeof(Foo), new Attribute[] {new FirstAttribute()}); 
    Console.WriteLine("First attempt: Filtering by passing an array with a new FirstAttribute"); 
    foreach (PropertyDescriptor propertyDescriptor in firstPropCollection) 
    { 
     Console.WriteLine(propertyDescriptor.Name); 
    } 

    Console.WriteLine(); 
    Console.WriteLine("Second attempt: Filtering by passing an an array with a new FirstAttribute with object initialization"); 
    var secondPropCollection = TypeDescriptor.GetProperties(typeof(Foo), new Attribute[] { new FirstAttribute {SomeFlag = true} }); 
    foreach (PropertyDescriptor propertyDescriptor in secondPropCollection) 
    { 
     Console.WriteLine(propertyDescriptor.Name); 
    } 

    Console.WriteLine(); 
    Console.WriteLine("Third attempt: I am quite ugly =(... but I work!"); 
    var thirdCollection = TypeDescriptor.GetProperties(typeof(Foo)).Cast<PropertyDescriptor>() 
     .Where(p => p.Attributes.Cast<Attribute>().Any(a => a.GetType() == typeof(FirstAttribute))); 
    foreach (PropertyDescriptor propertyDescriptor in thirdCollection) 
    { 
     Console.WriteLine(propertyDescriptor.Name); 
    } 

    Console.ReadLine(); 
} 

到目前为止,只有这样我让它成功运作是第三次尝试,我想知道是否有更直观更优雅的方式。

输出结果如下: enter image description here 正如你所看到的,我只能设法在最后一次尝试时获得两个属性。

在此先感谢

回答

1

我真的不知道我理解这个问题......你想有一个特定的属性,无论该属性值的所有属性?

class Program 
{ 
    static void Main(string[] args) 
    { 
     var props = typeof(Foo).GetProperties(); 
     var filtered = props 
      .Where(x => x.GetCustomAttributes(typeof(FirstAttribute), false).Length > 0) 
      .ToList(); 
     var propertyDescriptor = TypeDescriptor.GetProperties(typeof(Foo)) 
      .Find(filtered[0].Name, false); 
    } 
} 
class Foo 
{ 
    [First] 
    public string SomeString { get; set; } 

    [First(SomeFlag = true)] 
    public int SomeInt { get; set; } 
} 
[AttributeUsage(AttributeTargets.Property)] 
class FirstAttribute : Attribute 
{ 
    public bool SomeFlag { get; set; } 
} 
+0

你的解决方案的问题是你正在使用'PropertyInfo []'检索信息。我需要使用PropertyDescriptorCollection,因为我确实需要PropertyDescriptor来匹配每个与条件匹配的属性。 – taquion

+0

Type.GetProperties检索一个PropertyInfo数组 – taquion

+0

你是对的。编辑我的帖子。您可以从您在代码中迭代的集合中获取匹配描述符。但取决于你多久称此功能,你应该基准哪个功能更好地工作...... – Michael