Skip to content

Instantly share code, notes, and snippets.

@SeriaWei
Last active December 9, 2020 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SeriaWei/aeae127c364b4af9144e8b2bba1d752a to your computer and use it in GitHub Desktop.
Save SeriaWei/aeae127c364b4af9144e8b2bba1d752a to your computer and use it in GitHub Desktop.
C# Get Property Value With Emit
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