For properties there are GetGetMethod and GetSetMethod so that I can do:
Getter = (Func)Delegate.CreateDelegate(typeof(
ref return restriction in DynamicMethod seems to be gone at least on v4.0.30319.
Modified this answer by Glenn Slayden with info from microsoft docs:
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace ConsoleApp {
public class MyClass {
private int privateInt = 6;
}
internal static class Program {
private delegate ref TReturn OneParameter(TParameter0 p0);
private static void Main() {
var myClass = new MyClass();
var method = new DynamicMethod(
"methodName",
typeof(int).MakeByRefType(), // <- MakeByRefType() here
new[] {typeof(MyClass)},
typeof(MyClass),
true); // skip visibility
const BindingFlags bindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldflda, typeof(MyClass).GetField("privateInt", bindings));
il.Emit(OpCodes.Ret);
var getPrivateInt = (OneParameter) method.CreateDelegate(typeof(OneParameter));
Console.WriteLine(typeof(string).Assembly.ImageRuntimeVersion);
Console.WriteLine(getPrivateInt(myClass));
}
}
}
Outputs:
6