假设这个课程:
class Foo
{
public string Bar {get; set;}
public string Baz {get; set;}
}
如何使用反射查询以下列表:
List<Foo> list_of_foo = new List<Foo>()
{
new Foo() {Bar = "Hello", Baz = "Hola"} ,
new Foo() {Bar = "World!", Baz = "Mundo!"}
};
// match is found, and will hold the Foo with "Hello" and "Hola"
var match = list_of_foo.Single (ob => ob.Bar.Equals("Hello"));
// ------ My Question -----
// Lets assume I get the property I Need at run time:
string get_at_runtime = "Baz";
var prop_info = typeof(Foo).GetProperty(get_at_runtime);
// I can use the prop_info on the "match" variable like this:
var some_var = prop_info.GetValue(match) // some_var holds "Hola"
// But how can I do the following:
var some_foo = list_of_foo.Single ( f => f.prop_info.equals("Mundo!"));
答案 0 :(得分:1)
只需:
var some_foo = list_of_foo.Single(f => prop_info.GetValue(f).Equals("Mundo!"));
但如果属性值为null
,则会更安全:
var some_foo = list_of_foo.Single(f => "Mundo!".Equals(prop_info.GetValue(f)));