获取 T 的属性
Get properties of T
我想创建一些 class<T>
,然后在其中一个传递 T 对象 ("model") 的方法中,我需要访问 model.Property1
和 model.Property2
我需要将什么表达式传递给 class 构造函数来访问属性?
我在想这样的事情:
public MyClass(Expression<Func<T, object>> prop1, Expression<Func<T, object>> prop2)
但在这里我只找到了如何使用 MemberInfo 获取属性名称(我也需要):
void MyMethod(T model, ...)
{
Console.WriteLine(prop1.Member.Name)
}
我如何访问属性本身?
像 prop1.Invoke(model)
?
这样的东西
如果您使用如下方式为对象创建通用 class:
class MyClass<T, U>
where T : class
where U : struct
{ }
您可以创建一个接口,让您可以访问属性:
class IModel{
public int id {get; set;}
}
class MyClass<T, U>
where T : IModel
where U : struct
{ }
然后当您在代码中引用 T 时,您可以像这样从模型中访问 id:
class MyClass<T, U>
where T : IModel
where U : struct
{
public void DoStuff(T myModel){
int a = myModel.id;
}
}
不能直接执行表达式。为此,您需要将传递的 Expression<Func<..>>
转换为 Func<..>
,这是通过 Compile 方法实现的
void MyMethod(T model, ...)
{
var prop1Value1 = prop1.Compile()(model);
}
出于性能原因,您可以考虑在 class 构造函数中编译表达式并将生成的委托存储在 class 字段中。
此外,如果您只需要能够获取值,您可以考虑更改构造函数签名以接受 Func<..>
s 而不是
public MyClass(Func<T, object> prop1, Func<T, object> prop2)
如前所述,使用泛型(最好)或反射(较慢,保存较少)
object p1 = model.GetType().GetProperty("Property1").GetValue(model)
你也可以滥用动态(脏!),因为它基本上与反射相同
dynamic d = model;
object p1 = d.Property1;
我想创建一些 class<T>
,然后在其中一个传递 T 对象 ("model") 的方法中,我需要访问 model.Property1
和 model.Property2
我需要将什么表达式传递给 class 构造函数来访问属性?
我在想这样的事情:
public MyClass(Expression<Func<T, object>> prop1, Expression<Func<T, object>> prop2)
但在这里我只找到了如何使用 MemberInfo 获取属性名称(我也需要):
void MyMethod(T model, ...)
{
Console.WriteLine(prop1.Member.Name)
}
我如何访问属性本身?
像 prop1.Invoke(model)
?
如果您使用如下方式为对象创建通用 class:
class MyClass<T, U>
where T : class
where U : struct
{ }
您可以创建一个接口,让您可以访问属性:
class IModel{
public int id {get; set;}
}
class MyClass<T, U>
where T : IModel
where U : struct
{ }
然后当您在代码中引用 T 时,您可以像这样从模型中访问 id:
class MyClass<T, U>
where T : IModel
where U : struct
{
public void DoStuff(T myModel){
int a = myModel.id;
}
}
不能直接执行表达式。为此,您需要将传递的 Expression<Func<..>>
转换为 Func<..>
,这是通过 Compile 方法实现的
void MyMethod(T model, ...)
{
var prop1Value1 = prop1.Compile()(model);
}
出于性能原因,您可以考虑在 class 构造函数中编译表达式并将生成的委托存储在 class 字段中。
此外,如果您只需要能够获取值,您可以考虑更改构造函数签名以接受 Func<..>
s 而不是
public MyClass(Func<T, object> prop1, Func<T, object> prop2)
如前所述,使用泛型(最好)或反射(较慢,保存较少)
object p1 = model.GetType().GetProperty("Property1").GetValue(model)
你也可以滥用动态(脏!),因为它基本上与反射相同
dynamic d = model;
object p1 = d.Property1;