Skip to main content
 首页 » 编程设计

c#之通过属性及其值获取属性名称

2024年02月13日11dyllove98

所以我正在用 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 中的对象。

请您参考如下方法:

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

使用 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: {pa.Property.Name}, PropertyValue: {value}, AttributeName: {pa.Attribute.GetType().Name}"); 
    } 
}