.Net:如何使用TypeDescriptor.GetProperties获取自定义属性?

ctr*_*yan 3 .net custom-attributes typedescriptor

我创建了自己的属性来装饰我的对象.

 [AttributeUsage(AttributeTargets.All)]
    public class MyCustomAttribute : System.Attribute { }
Run Code Online (Sandbox Code Playgroud)

当我尝试使用传入我的自定义属性的TypeDescriptor.GetProperties时,即使使用该属性修饰了类型,它也不会返回任何内容.

  var props = TypeDescriptor.GetProperties(
              type, 
              new[] { new Attributes.FlatLoopValueInjection()});
Run Code Online (Sandbox Code Playgroud)

如何让TypeDescriptor.GetProperties识别我的自定义类型?

Dmi*_*ryG 8

所述Type.GetProperties(类型,属性[])方法返回的唯一集合属性为指定的类型的组件的使用属性作为过滤器的一个指定的数组.
您确定目标类型是否具有使用自定义属性标记的属性,如下所示?

//...
    var props = TypeDescriptor.GetProperties(typeof(Person), new Attribute[] { new NoteAttribute() });
    PropertyDescriptor nameProperty = props["Name"];
}
//...
class Person {
    [Note]
    public string Name { get; set; }
}
//...
class NoteAttribute : Attribute {
/* implementation */
}
Run Code Online (Sandbox Code Playgroud)