2011-11-03 68 views
3

我已经创建了自己的属性来装饰我的对象。.Net:如何使用TypeDescriptor.GetProperties获取自定义属性?

[AttributeUsage(AttributeTargets.All)] 
    public class MyCustomAttribute : System.Attribute { } 

当我尝试使用TypeDescriptor.GetProperties传入我的自定义属性不返回即使型装饰与属性什么。

var props = TypeDescriptor.GetProperties(
       type, 
       new[] { new Attributes.FlatLoopValueInjection()}); 

我怎么TypeDescriptor.GetProperties承认我的自定义类型?

回答

8

Type.GetProperties(type, Attributes[])方法只返回为特定类型的组件使用指定的属性数组作为过滤器的属性的集合。
确定目标类型有打上您的自定义一个属性的属性,这样的吗?

//... 
    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 */ 
} 
0

更新以获得财产属性

这个代码是复制和MSDN,这是谷歌搜索“get customattribute reflection c#”的第一个结果粘贴

using System; 

public class ExampleAttribute : Attribute 
{ 
    private string stringVal; 

    public ExampleAttribute() 
    { 
     stringVal = "This is the default string."; 
    } 

    public string StringValue 
    { 
     get { return stringVal; } 
     set { stringVal = value; } 
    } 
} 

[Example(StringValue="This is a string.")] 
class Class1 
{ 
    public static void Main() 
    { 
     PropertyInfo propertyInfo = typeof (Class1).GetProperties().Where(p => p.Name == "Foo").FirstOrDefault(); 
     foreach (object attrib in propertyInfo.GetCustomAttributes(true)) 
     { 
      Console.WriteLine(attrib); 
     } 
    } 

    [Example(StringValue = "property attribute")] 
    public string Foo {get;set;} 
} 
+0

为什么downvote?这不是回答这个问题吗? – Jason

+0

不是我的,但我认为他正试图访问属性上的属性,而不是自己的类。 –

相关问题