Compare/access 使用字符串引用动态对象的属性
Compare/access object's properties dynamically with string reference
我有一个简单的class:
class Event {
public string Source { get; set; }
}
然后我有一个列表 class:
var list = new List<Event>();
list.Add(new Event { Source="Me" });
list.Add(new Event { Source="You" });
现在我想在列表中获得一个 "Source" 属性 设置为 "Me" 的事件。
但我不想像这个列表[0]那样访问这个属性。来源像这样:
list.Where(o => o.Source == "Me").Single()
我知道我的对象有 "Source" 属性。但我需要传递一个字符串来获取这个 属性 并进行比较。像这样:
list.Where(o => o.GetType().GetProperty("Source").GetType() == "Me").Single()
显然,这不起作用。基本上,我需要能够在不直接引用 属性 的情况下编写类似 o.Source == "ME"
的比较。
我该怎么做?
您需要改用 GetValue
方法
list.Where(o => o.GetType().GetProperty("Source").GetValue(o, null) == "Me").Single()
我有一个简单的class:
class Event {
public string Source { get; set; }
}
然后我有一个列表 class:
var list = new List<Event>();
list.Add(new Event { Source="Me" });
list.Add(new Event { Source="You" });
现在我想在列表中获得一个 "Source" 属性 设置为 "Me" 的事件。
但我不想像这个列表[0]那样访问这个属性。来源像这样:
list.Where(o => o.Source == "Me").Single()
我知道我的对象有 "Source" 属性。但我需要传递一个字符串来获取这个 属性 并进行比较。像这样:
list.Where(o => o.GetType().GetProperty("Source").GetType() == "Me").Single()
显然,这不起作用。基本上,我需要能够在不直接引用 属性 的情况下编写类似 o.Source == "ME"
的比较。
我该怎么做?
您需要改用 GetValue
方法
list.Where(o => o.GetType().GetProperty("Source").GetValue(o, null) == "Me").Single()