如何返回表达式<func <tclass,tclassfield =“”>&gt;只给出FieldInfo和TClass?

时间:2015-11-01 10:29:03

标签: .net generics reflection lambda expression-trees

在运行时我只有TClassFieldInfo,我需要生成一个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);

1 个答案:

答案 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 );