通过表达式树编译动态实例方法,具有私有和受保护的访问权限?

Compile dynamic instance method by expression tree, with this, private and protected access?

是否可以在 C#(或其他 .NET 语言)中创建动态方法作为现有类型的实例方法,并访问 "this" 引用、私有和受保护成员?

在不绕过可见性限制的情况下对 private/protected 成员的合法访问对我来说非常重要,因为使用 DynamicMethod 是可能的。

Expression.Lambda CompileToMethod(MethodBuilder) 调用对我来说看起来非常复杂,而且我还找不到为已经存在的 type/module

创建合适的 MethodBuilder 的方法

编辑:我现在从表达式树创建了一个副本 Action,就像一个 static/extension 方法。 Expression.Property(...) 访问是由 Reflection (PropertyInfo) 定义的,如果通过 Reflection 定义,我可以访问 private/protected 成员。不像 DynamicMethod 和发出的 IL 那样好,其中生成的方法的行为类似于具有可见性检查的成员(甚至比普通的 C# 复制代码快一点),但表达式树似乎更易于维护。

像这样,在使用 DynamicMethod 和 Reflection.Emit 时:

public static DynamicMethod GetDynamicCopyValuesMethod()
{
    var dynamicMethod = new DynamicMethod(
        "DynLoad",
        null, // return value type (here: void)
        new[] { typeof(DestClass), typeof(ISourceClass) }, 
            // par1: instance (this), par2: method parameter
        typeof(DestClass)); 
            // class type, not Module reference, to access private properties.

        // generate IL here
        // ...
}

// class where to add dynamic instance method   

public class DestClass
{
    internal delegate void CopySourceDestValuesDelegate(ISourceClass source);

    private static readonly DynamicMethod _dynLoadMethod = 
        DynamicMethodsBuilder.GetDynamicIlLoadMethod();

    private readonly CopySourceDestValuesDelegate _copySourceValuesDynamic;

    public DestClass(ISourceClass valuesSource) // constructor
    {
        _valuesSource = valuesSource;
        _copySourceValuesDynamic = 
            (LoadValuesDelegate)_dynLoadMethod.CreateDelegate(
                typeof(CopySourceDestValuesDelegate), this);
                // important: this as first parameter!
    }

    public void CopyValuesFromSource()
    {
        copySourceValuesDynamic(_valuesSource); // call dynamic method
    }

    // to be copied from ISourceClass instance
    public int IntValue { get; set; } 

    // more properties to get values from ISourceClass...
}

此动态方法可以访问具有完整可见性检查的 DestClass private/protected 成员。

编译表达式树时是否有等效项?

我已经这样做了很多次,所以您可以使用这样的代码轻松访问某个类型的任何受保护成员:

static Action<object, object> CompileCopyMembersAction(Type sourceType, Type destinationType)
{
    // Action input args: void Copy(object sourceObj, object destinationObj)
    var sourceObj = Expression.Parameter(typeof(object));
    var destinationObj = Expression.Parameter(typeof(object));

    var source = Expression.Variable(sourceType);
    var destination = Expression.Variable(destinationType);

    var bodyVariables = new List<ParameterExpression>
    {
        // Declare variables:
        // TSource source;
        // TDestination destination;
        source,
        destination
    };

    var bodyStatements = new List<Expression>
    {
        // Convert input args to needed types:
        // source = (TSource)sourceObj;
        // destination = (TDestination)destinationObj;
        Expression.Assign(source, Expression.ConvertChecked(sourceObj, sourceType)),
        Expression.Assign(destination, Expression.ConvertChecked(destinationObj, destinationType))
    };

    // TODO 1: Use reflection to go through TSource and TDestination,
    // find their members (fields and properties), and make matches.
    Dictionary<MemberInfo, MemberInfo> membersToCopyMap = null;

    foreach (var pair in membersToCopyMap)
    {
        var sourceMember = pair.Key;
        var destinationMember = pair.Value;

        // This gives access: source.MyFieldOrProperty
        Expression valueToCopy = Expression.MakeMemberAccess(source, sourceMember);

        // TODO 2: You can call a function that converts source member value type to destination's one if they don't match:
        // valueToCopy = Expression.Call(myConversionFunctionMethodInfo, valueToCopy);

        // TODO 3: Additionally you can call IClonable.Clone on the valueToCopy if it implements such interface.
        // Code: source.MyFieldOrProperty == null ? source.MyFieldOrProperty : (TMemberValue)((ICloneable)source.MyFieldOrProperty).Clone()
        //if (typeof(ICloneable).IsAssignableFrom(valueToCopy.Type))
        //    valueToCopy = Expression.IfThenElse(
        //        test: Expression.Equal(valueToCopy, Expression.Constant(null, valueToCopy.Type)),
        //        ifTrue: valueToCopy,
        //        ifFalse: Expression.Convert(Expression.Call(Expression.Convert(valueToCopy, typeof(ICloneable)), typeof(ICloneable).GetMethod(nameof(ICloneable.Clone))), valueToCopy.Type));

        // destination.MyFieldOrProperty = source.MyFieldOrProperty;
        bodyStatements.Add(Expression.Assign(Expression.MakeMemberAccess(destination, destinationMember), valueToCopy));
    }

    // The last statement in a function is: return true;
    // This is needed, because LambdaExpression cannot compile an Action<>, it can do Func<> only,
    // so the result of a compiled function does not matter - it can be any constant.
    bodyStatements.Add(Expression.Constant(true));

    var lambda = Expression.Lambda(Expression.Block(bodyVariables, bodyStatements), sourceObj, destinationObj);
    var func = (Func<object, object, bool>)lambda.Compile();

    // Decorate Func with Action, because we don't need any result
    return (src, dst) => func(src, dst);
}

这将编译一个将成员从一个对象复制到另一个对象的操作(不过请参阅 TODO 列表)。