Created
September 27, 2019 04:34
-
-
Save idkiller/9a80285b6f11aa76aae591c8730f51ed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class DynamicAccessor | |
| { | |
| object obj; | |
| public Func<object, object> Getter; | |
| public Action<object, object> Setter; | |
| public DynamicAccessor(object obj, string propertyName) | |
| { | |
| this.obj = obj; | |
| DynamicMethod getter = new DynamicMethod("getter",typeof(object), new Type[] { typeof(object) }); | |
| WriteGetter(getter, propertyName); | |
| DynamicMethod setter = new DynamicMethod("setter", null, new Type[] { typeof(object), typeof(object) }); | |
| writeSetter(setter, propertyName); | |
| Getter = (Func<object, object>)getter.CreateDelegate(typeof(Func<object, object>)); | |
| Setter = (Action<object, object>)setter.CreateDelegate(typeof(Action<object, object>)); | |
| } | |
| private void writeSetter(DynamicMethod md, string propertyName) | |
| { | |
| var mi = obj.GetType().GetProperty(propertyName).SetMethod; | |
| var il = md.GetILGenerator(); | |
| il.Emit(OpCodes.Ldarg_0); | |
| il.Emit(OpCodes.Ldarg_1); | |
| il.Emit(OpCodes.Callvirt, mi); | |
| il.Emit(OpCodes.Nop); | |
| il.Emit(OpCodes.Ret); | |
| } | |
| private void WriteGetter(DynamicMethod md, string propertyName) | |
| { | |
| var mi = obj.GetType().GetProperty(propertyName).GetMethod; | |
| var il = md.GetILGenerator(); | |
| il.Emit(OpCodes.Ldarg_0); | |
| il.Emit(OpCodes.Callvirt, mi); | |
| il.Emit(OpCodes.Ret); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment