Is there a way to create a delegate to get and set values for a FieldInfo?

后端 未结 8 2005
闹比i
闹比i 2020-12-08 08:18

For properties there are GetGetMethod and GetSetMethod so that I can do:

Getter = (Func)Delegate.CreateDelegate(typeof(         


        
8条回答
  •  死守一世寂寞
    2020-12-08 08:35

    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
    

提交回复
热议问题