【问题标题】:.Net: How to I get Custom Attributes using TypeDescriptor.GetProperties?.Net:如何使用 TypeDescriptor.GetProperties 获取自定义属性?
【发布时间】:2011-11-03 14:53:04
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: .net custom-attributes typedescriptor


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      已更新以获取属性属性

      此代码是从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;}
      }
      

      【讨论】:

      • 不是我的,但我认为他正在尝试访问属性上的属性,而不是类本身。
      • TypeDescriptor 可以稍后注入属性。它就像反射的可扩展版本。如果TypeDescriptor OP需要什么,那么这个答案是错误的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-29
      • 1970-01-01
      • 2017-09-19
      • 2011-01-24
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多