按属性及其值获取属性名称

时间:2014-03-20 16:40:54

标签: c# properties attributes

因此,我正在使用C#中的项目来获取属性及其值的属性名称。我有一个集合:

ObservableCollection<Entity> collection = new ObsevableCollection<Entity>();
collection.Add(new Entity { Id = 5, Description = "Pizza" });
collection.Add(new Entity { Id = 2, Description = "Coca cola" });
collection.Add(new Entity { Id = 1, Description = "Broccoli" });

,实体包括:

class Entity
{
    public int Id { get; set; }

    [MyAttribute]
    public string Description { get; set; }

    // other properties
}

我的问题是:是否可以在具有属性MyAttribute的实体中获取特定属性及其值。这都来自collection的对象。

2 个答案:

答案 0 :(得分:3)

使用GetCustomAttributes查找属性,使用LINQ过滤并获取一个包含Prorties和属性的匿名对象。

使用PropertyInfo.GetValue读取实际值。

但请注意,反射调用非常昂贵:

var propertiesWithAttribute = typeof(Entity).GetProperties()
    // use projection to get properties with their attributes - 
    .Select(pi => new { Property = pi, Attribute = pi.GetCustomAttributes(typeof(MyAttribute), true).FirstOrDefault() as MyAttribute})
    // filter only properties with attributes
    .Where(x => x.Attribute != null)
    .ToList();

foreach (Entity entity in collection)
{
    foreach (var pa in propertiesWithAttribute)
    {
        object value = pa.Property.GetValue(entity, null);
        Console.WriteLine("PropertyName: {0}, PropertyValue: {1}, AttributeName: {2}", pa.Property.Name, value, pa.Attribute.GetType().Name);
    }
}

答案 1 :(得分:0)

您的问题是:是否可以获取具有属性MyAttribute的实体中的特定属性及其值。

答案:当然可能

接下来的问题将是如何!!

简短回答:使用反思

以下链接中的长答案

reflections-to-get-attribute-value

请注意以下摘录:

// Using reflection.


 System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // Reflection. 
// Displaying output. 
foreach (System.Attribute attr in attrs)
{
    if (attr is Author)
    {
        Author a = (Author)attr;
        System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);
    }
}