Search code examples
c#.netexpressionreflection.emitdynamicmethod

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


Is it possible to create a dynamic method in C# (or possibly other .NET languages) as an instance method of an already existing type, with access to "this" reference, private and protected members?

A legitimate access to private/protected members, without circumventing visibility limits, is quite important for me, as it is possible with DynamicMethod.

The Expression.Lambda CompileToMethod(MethodBuilder) call looks very complicated for me, and I could not yet find a way to create a proper MethodBuilder for an already existing type/module

EDIT: I now created a copy Action<DestClass, ISourceClass>, like a static/extension method, from an Expression tree. Expression.Property(...) access is defined by Reflection (PropertyInfo) anyway, and I can access private/protected members, if defined through Reflection. Not as nice as with DynamicMethod and emitted IL, where the generated method behaves like a member with visibility checks (and is even a bit faster than ordinary C# copy code), but Expression trees seem to be far better to maintain.

Like this, when working with DynamicMethod and 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...
}

This dynamic method can access DestClass private/protected members with full visibility checks.

Is there any equivalent when compiling an Expression tree?


Solution

  • I've done this many times, so you can easily access any protected member of a type with such code:

    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);
    }
    

    This will compile an action which copies members from one object to another (see TODO list though).