gpt4 book ai didi

c# - 通过表达式树编译动态实例方法,具有私有(private)和 protected 访问权限?

转载 作者:行者123 更新时间:2023-11-30 17:36:35 27 4
gpt4 key购买 nike

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

在不绕过可见性限制的情况下对私有(private)/ protected 成员的合法访问对我来说非常重要,因为使用 DynamicMethod 可以做到这一点。

Expression.Lambda CompileToMethod(MethodBuilder) 调用对我来说看起来非常复杂,而且我还找不到为现有类型/模块创建合适的 MethodBuilder 的方法

编辑:我现在从表达式树创建了一个副本 Action ,就像静态/扩展方法一样。无论如何,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 成员。

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

最佳答案

我已经这样做了很多次,所以您可以使用这样的代码轻松访问某个类型的任何 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 列表)。

关于c# - 通过表达式树编译动态实例方法,具有私有(private)和 protected 访问权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39207253/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com