简体   繁体   English

将访问属性属性作为实例属性-可以吗?

[英]Access attribute properties as instance properties - is it possible?

For example, I have a class with a property and attributes: 例如,我有一个带有属性和属性的类:

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

I want to get the attribute values like 我想获得像

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

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

How to get it? 如何获得? I want the code that automatically fill the additional fields of MyClass with attribute data. 我想要用属性数据自动填充MyClass的其他字段的代码。 It seems to be very convenient to access to the attribute values like to the instance values - for bindings, etc. 像访问实例值一样访问属性值似乎非常方便-用于绑定等。

The main complexity is to fill MyClass.Attributes and MyClass.Properties collections with objects with names the same as properties and attributes names. 主要的复杂性是用名称与属性和属性名称相同的对象填充MyClass.Attributes和MyClass.Properties集合。 And so I think this collections must be static. 因此,我认为这些集合必须是静态的。 And each object inside MyClass.Properties collection also must has Attributes collection (for example, MyProperty.Attributes) like MyClass.Attributes collection. 并且MyClass.Properties集合内的每个对象还必须具有Attributes集合(例如MyProperty.Attributes),例如MyClass.Attributes集合。

I'm not sure what you are trying to achieve, but below code will make you an idea how to extract attribute data from your assembly at run-time. 我不确定您要实现的目标,但是下面的代码将使您了解如何在运行时从程序集中提取属性数据。 Please note that attribute data is per type declaration, not per instance of type. 请注意,属性数据是按类型声明而不是类型实例的。

    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);
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM