在运行时我只有TClass
和FieldInfo
,我需要生成一个lambda表达式,它获取TClass
的实例并返回correlate字段。在构建MemberExpression
之后,我试图将表达式包装到Expression<Func<TClass, TClassField>>
时遇到困难:
var res = Expression.Lambda<Func<TClass, TClassField>>(memberExpression, paramExp);
return res;
因为在编译期间不知道TClassField。由于第三方的要求,我需要一些强类型的解决方案(没有转换为object
)。这在C#中是否可行?
private void User3rdPartyLibrary<TClass>(FieldInfo fi)
{
//Goal: call _3rdParty.Method<TClass, TClassField>(expression)
var memberExp = Expression.Field(Expression.Parameter(typeof(TClass)), fi);
//var lambda = some magic that returns Expression.Lambda<Func<TClass, TClassField>>
// where fi.FieldType == typeof(TClassField).
//_3rdParty.Method(lambda);
}
签署第三方方法:
public void Method<TClass, TClassMember>(Expression<Func<TClass, TClassMember>> expression);
答案 0 :(得分:2)
public static void User3rdPartyLibrary<TClass>( FieldInfo fi )
{
// check types; add descriptions to exceptions
if( fi.ReflectedType != typeof( TClass ) )
{
throw new ArgumentException();
}
var pe = Expression.Parameter( typeof( TClass ) );
var me = Expression.Field( pe, fi );
var memberExpression = Expression.Lambda( me, pe );
// GetMethod call inlined for illustrative purposes
typeof( ThirdPartyClass ).GetMethod( "ThirdPartyMethod" )
.MakeGenericMethod( typeof( TClass ), fi.FieldType )
.Invoke( memberExpression );
}
然后使用反射调用:
FieldInfo fi = <whatever>;
// again, GetMethod call inlined for illustrative purposes
typeof( YourType ).GetMethod( "User3rdPartyLibrary" )
.MakeGenericMethod( fi.ReflectedType )
.Invoke( fi );