C# 使用表达式获取属性的get Acessor
我想获取属性的get Acessor(C# 使用表达式获取属性的get Acessor,c#,api,reflection,lambda,expression,C#,Api,Reflection,Lambda,Expression,我想获取属性的get Acessor(PropertyInfo)并将其编译为Func。声明类型仅在运行时已知 我目前的代码是: public Func<Object, Object> CompilePropGetter(PropertyInfo info) { MethodInfo getter = info.GetGetMethod(); ParameterExpression instance = Expression.Parameter(info.Declar
PropertyInfo
)并将其编译为Func
。声明类型仅在运行时已知
我目前的代码是:
public Func<Object, Object> CompilePropGetter(PropertyInfo info)
{
MethodInfo getter = info.GetGetMethod();
ParameterExpression instance = Expression.Parameter(info.DeclaringType, info.DeclaringType.Name);
MethodCallExpression setterCall = Expression.Call(instance, getter);
Expression getvalueExp = Expression.Lambda(setterCall, instance);
Expression<Func<object, object>> GetPropertyValue = (Expression<Func<object, object>>)getvalueExp;
return GetPropertyValue.Compile();
}
那么,如何返回
Func
?您可以使用表达式向预期类型和返回类型添加强制转换。Convert
:
public static Func<Object, Object> CompilePropGetter(PropertyInfo info)
{
ParameterExpression instance = Expression.Parameter(typeof(object));
var propExpr = Expression.Property(Expression.Convert(instance, info.DeclaringType), info);
var castExpr = Expression.Convert(propExpr, typeof(object));
var body = Expression.Lambda<Func<object, object>>(castExpr, instance);
return body.Compile();
}
publicstaticfunc编译器复制程序(PropertyInfo-info)
{
ParameterExpression实例=Expression.Parameter(typeof(object));
var propExpr=Expression.Property(Expression.Convert(instance,info.DeclaringType),info);
var castExpr=Expression.Convert(propExpr,typeof(object));
var body=Expression.Lambda(castExpr,instance);
返回body.Compile();
}
您可以使用表达式将强制转换添加到预期类型和返回类型。Convert
:
public static Func<Object, Object> CompilePropGetter(PropertyInfo info)
{
ParameterExpression instance = Expression.Parameter(typeof(object));
var propExpr = Expression.Property(Expression.Convert(instance, info.DeclaringType), info);
var castExpr = Expression.Convert(propExpr, typeof(object));
var body = Expression.Lambda<Func<object, object>>(castExpr, instance);
return body.Compile();
}
publicstaticfunc编译器复制程序(PropertyInfo-info)
{
ParameterExpression实例=Expression.Parameter(typeof(object));
var propExpr=Expression.Property(Expression.Convert(instance,info.DeclaringType),info);
var castExpr=Expression.Convert(propExpr,typeof(object));
var body=Expression.Lambda(castExpr,instance);
返回body.Compile();
}