如何 Return Expression<Func<TClass, TClassField>> 当仅给出 FieldInfo 和 TClass 时?

How to Return Expression<Func<TClass, TClassField>> when given only FieldInfo and TClass?

在运行时我只有 TClass 和一个 FieldInfo,我需要生成一个 lambda 表达式来获取 TClass 和 returns 相关字段的实例.构建 MemberExpression 后,我在尝试将表达式包装为 Expression<Func<TClass, TClassField>>:

时卡住了
var res = Expression.Lambda<Func<TClass, TClassField>>(memberExpression, paramExp);
return res;

因为 TClassField 在编译期间是未知的。由于第 3 方要求,我需要一些强类型的解决方案(不强制转换为 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);
}

第3方方法签名:

public void Method<TClass, TClassMember>(Expression<Func<TClass, TClassMember>> expression);
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 );