[英]Get property name by attribute and its value
所以我正在用 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 过滤并获取包含属性和属性的匿名对象。
使用 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}");
}
}
您的问题是:是否可以在具有属性 MyAttribute 及其值的实体中获取特定属性。
答:当然可以
那么下一个问题将是如何!
简短回答:使用反射
以下链接中的长答案
请注意以下摘录:
// 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.