一,泛型反射优化:基本思路,根据泛型缓存原理(静态构造+静态字段)
public class Accessor<S> { /// <summary> /// 属性类型 /// </summary> public static PropertyInfo[] PropertyTypes { get; private set; } /// <summary> /// 实体类型 /// </summary> public static Type type { get; private set; } static Accessor() { type = typeof(S); PropertyTypes = type.GetProperties(); } }
二,调用逻辑
Stopwatch st = new Stopwatch(); st.Start(); for (int i = 0; i < 10000000; i++) { var ss = Accessor<Person>.PropertyTypes; } st.Stop(); var str1 = st.ElapsedMilliseconds.ToString(); st.Reset(); st.Start(); for (int i = 0; i < 10000000; i++) { Type type = typeof(Person); var ss = type.GetProperties(); } st.Stop(); var str2 = st.ElapsedMilliseconds.ToString();