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?