首页 文章

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

提问于
浏览
2

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

合法访问私有/受保护成员,而不会绕过可见性限制,对我来说非常重要,因为DynamicMethod可以实现 .

Expression.Lambda CompileToMethod(MethodBuilder)调用对我来说看起来很复杂,我还没有找到为现有类型/模块创建正确的MethodBuilder的方法

编辑:我现在从表达式树创建了一个副本Action <DestClass,ISourceClass>,就像一个静态/扩展方法 . 无论如何,Expression.Property(...)访问由Reflection(PropertyInfo)定义,如果通过Reflection定义,我可以访问私有/受保护成员 . 不像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私有/受保护成员 .

编译表达式树时是否有任何等价物?

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列表) .

相关问题