use*_*962 3 c# attributes properties
因此,我正在使用 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" });
Run Code Online (Sandbox Code Playgroud)
该实体包括:
class Entity
{
public int Id { get; set; }
[MyAttribute]
public string Description { get; set; }
// other properties
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:是否可以获取具有 MyAttribute 属性及其值的实体中的特定属性。这全部来自 的对象collection。
使用 GetCustomAttributes 查找属性,并使用 LINQ 过滤并获取保存属性和属性的匿名对象。
使用 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}");
}
}
Run Code Online (Sandbox Code Playgroud)