【问题标题】:Access attribute properties as instance properties - is it possible?将属性属性作为实例属性访问 - 有可能吗?
【发布时间】:2013-02-10 12:05:51
【问题描述】:

例如,我有一个带有属性和属性的类:

[MyDisplay(Name = "Class name", Description = "Class description.")]
public class MyClass
{
    [MyDisplay(Name = "Property name", Description = "Property description.")]
    public int MyProperty { get; set; }
}

我想得到类似的属性值

// Get type attribute...
string className = MyClass.Attributes.MyDisplay.Name;

// Get member attribute...
string propertyDescription =
    MyClass.Properties.MyProperty.Attributes.MyDisplay.Description;

如何获得?我想要使​​用属性数据自动填充 MyClass 的附加字段的代码。访问实例值等属性值似乎非常方便 - 用于绑定等。

主要的复杂性是用名称与属性和属性名称相同的对象填充 MyClass.Attributes 和 MyClass.Properties 集合。所以我认为这个集合必须是静态的。并且 MyClass.Properties 集合中的每个对象也必须像 MyClass.Attributes 集合一样具有 Attributes 集合(例如 MyProperty.Attributes)。

【问题讨论】:

  • “实例级别属性”是什么意思?你想如何在你的代码中声明?
  • 属性“显示”在 MyClass 上无效。它仅对“方法、属性、索引器、字段、参数”声明有效。还是您实现了自己的 Display 属性?
  • rene,它可以是类的任何有效属性。为了清楚起见,我更改了它的名称。

标签: c# properties attributes


【解决方案1】:

我不确定您想要实现什么,但下面的代码会让您了解如何在运行时从程序集中提取属性数据。请注意,属性数据是每个类型声明的,而不是每个类型实例的。

    foreach (var type in System.Reflection.Assembly.GetExecutingAssembly().GetTypes())
    {
        // class attributes
        foreach (var typeAttr in type.GetCustomAttributes(typeof(DisplayAttribute), false))
        {
            Console.WriteLine(((DisplayAttribute)typeAttr).Name);
            Console.WriteLine(((DisplayAttribute)typeAttr).Description);
        }

        // members attributes
        foreach (var props in type.GetProperties())
        {
            foreach (var propsAttr in props.GetCustomAttributes(typeof(DisplayAttribute), false))
            {
                Console.WriteLine(((DisplayAttribute)propsAttr).Name);
                Console.WriteLine(((DisplayAttribute)propsAttr).Description);
            }
        }
    }

【讨论】:

  • 哦,我有点误会了!所以,我知道如何获取属性及其属性。我只想将它们组织为类型的字段。为了清楚起见,我修正了我的问题。
猜你喜欢
  • 2013-11-18
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 2010-11-21
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多