3

「this」参照、プライベート、および保護されたメンバーにアクセスして、既存の型のインスタンス メソッドとして C# (または他の .NET 言語) で動的メソッドを作成することは可能ですか?

可視性の制限を回避することなく、プライベート/保護されたメンバーへの正当なアクセスは、DynamicMethod で可能になるため、私にとって非常に重要です。

Expression.Lambda CompileToMethod(MethodBuilder) 呼び出しは非常に複雑に見えますが、既存の型/モジュールに対して適切な MethodBuilder を作成する方法をまだ見つけることができませんでした

編集: 式ツリーから、静的/拡張メソッドのように、Action<DestClass, ISourceClass> のコピーを作成しました。いずれにせよ Expression.Property(...) アクセスは Reflection (PropertyInfo) によって定義され、Reflection を介して定義されている場合は、プライベート/保護されたメンバーにアクセスできます。生成されたメソッドが可視性チェックを備えたメンバーのように動作する (通常の C# コピー コードよりも少し高速である) DynamicMethod および発行された IL ほど良くはありませんが、式ツリーは維持するのにはるかに優れているようです。

このように、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 のプライベート/保護されたメンバーにアクセスできます。

式ツリーをコンパイルするときに同等のものはありますか?

4

1 に答える 1

1

私はこれを何度も行ってきたので、そのようなコードを使用して、型の保護されたメンバーに簡単にアクセスできます。

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 リストを参照してください)。

于 2016-08-30T15:39:12.623 に答える