Last active
October 24, 2023 16:51
-
-
Save KOZ60/2c2901cabb442a9e424418b090c30475 to your computer and use it in GitHub Desktop.
GetProperties
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
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Diagnostics; | |
using System.Linq.Expressions; | |
using System.Reflection; | |
class OrderPoco | |
{ | |
public int OrderID { get; set; } | |
public string CustomerID { get; set; } | |
public int Shipper { get; set; } | |
} | |
internal class Program | |
{ | |
static void Main(string[] args) { | |
var o = new OrderPoco() { | |
OrderID = 1, | |
CustomerID = "ABCDE", | |
Shipper = 3 | |
}; | |
UseTypeDesctiptor(o); | |
UseReflection(o); | |
UseExpression(o); | |
Console.ReadKey(); | |
} | |
static void Watch(Action action) { | |
var sw = new Stopwatch(); | |
sw.Start(); | |
for (int i = 0; i < LoopCount; i++) { | |
action.Invoke(); | |
} | |
sw.Stop(); | |
Console.WriteLine($"{sw.ElapsedMilliseconds} ms"); | |
} | |
const int LoopCount = 1000000; | |
static void UseTypeDesctiptor(object obj) { | |
var properties = TypeDescriptor.GetProperties(obj); | |
foreach (PropertyDescriptor property in properties) { | |
string propertyName = property.Name; | |
object propertyValue = property.GetValue(obj); | |
Console.WriteLine($"{propertyName}: {propertyValue}"); | |
} | |
Watch(() => { | |
foreach (PropertyDescriptor pi in properties) { | |
var value = pi.GetValue(obj); | |
} | |
}); | |
} | |
static void UseReflection<T>(T obj) { | |
var properties = typeof(T).GetProperties(); | |
foreach (PropertyInfo pi in properties) { | |
string propertyName = pi.Name; | |
object propertyValue = pi.GetValue(obj); | |
Console.WriteLine($"{propertyName}: {propertyValue}"); | |
} | |
Watch(() => { | |
foreach (var pi in properties) { | |
var value = pi.GetValue(obj); | |
} | |
}); | |
} | |
static void UseExpression<T>(T obj) { | |
var type = typeof(T); | |
var parameter = Expression.Parameter(type); | |
var dic = new Dictionary<string, Func<T, object>>(); | |
foreach (PropertyInfo pi in type.GetProperties()) { | |
var property = Expression.Property(parameter, pi); | |
var conversion = Expression.Convert(property, typeof(object)); | |
var lambda = Expression.Lambda<Func<T, object>>(conversion, parameter); | |
Func<T, object> function = lambda.Compile(); | |
dic.Add(pi.Name, function); | |
} | |
foreach (var kp in dic) { | |
Console.WriteLine($"{kp.Key}: {kp.Value(obj)}"); | |
} | |
Watch(() => { | |
foreach (var kp in dic) { | |
var value = kp.Value(obj); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment