Last active
December 9, 2020 13:52
-
-
Save SeriaWei/aeae127c364b4af9144e8b2bba1d752a to your computer and use it in GitHub Desktop.
C# Get Property Value With Emit
This file contains 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
private static void Emit() | |
{ | |
People people = new People { Name = "Wayne" }; | |
Type type = typeof(People); | |
var property = type.GetProperty("Name"); | |
DynamicMethod method = new DynamicMethod("GetPropertyValue", typeof(object), new Type[] { type }, true); | |
ILGenerator il = method.GetILGenerator(); | |
il.Emit(OpCodes.Ldarg_0); | |
il.Emit(OpCodes.Callvirt, property.GetGetMethod()); | |
if (property.PropertyType.IsValueType) | |
{ | |
il.Emit(OpCodes.Box, property.PropertyType); | |
} | |
il.Emit(OpCodes.Ret); | |
Func<People, object> fun = method.CreateDelegate(typeof(Func<People, object>)) as Func<People, object>; | |
Stopwatch stopwatch = Stopwatch.StartNew(); | |
for (int i = 0; i < 10000000; i++) | |
{ | |
object value = fun.Invoke(people); | |
} | |
stopwatch.Stop(); | |
Console.WriteLine("Emit:{0}ms", stopwatch.ElapsedMilliseconds); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment