62,046
社区成员
发帖
与我相关
我的任务
分享
struct EntityPropInfo
{
public readonly string PropertyName;
public readonly Type Type;
public readonly MethodInfo GetMethod;
public EntityPropInfo(PropertyInfo prop)
{
PropertyName = prop.Name;
Type = prop.PropertyType;
GetMethod = prop.GetGetMethod(false);
}
}
private Func<T, List<object>> GetDelegate(List<EntityPropInfo> lepis)
{
Type type = typeof(T);
var dm = new DynamicMethod("getValue1", typeof(List<object>), new Type[] { type }, true);
ILGenerator il = dm.GetILGenerator();
LocalBuilder list = il.DeclareLocal(typeof(List<object>));
il.Emit(OpCodes.Newobj, typeof(List<object>).GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Stloc_S, list);
for (int i = 0; i < lepis.Count; ++i)
{
LocalBuilder obj = il.DeclareLocal(lepis[i].Type);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Stloc, obj);
il.Emit(OpCodes.Call, lepis[i].GetMethod);
if (lepis[i].Type.IsValueType)
{
il.Emit(OpCodes.Box, lepis[i].Type);
}
il.Emit(OpCodes.Ldloc, list);
il.Emit(OpCodes.Ldloc, obj);
il.Emit(OpCodes.Callvirt, typeof(List<object>).GetMethod("Add"));
}
il.Emit(OpCodes.Ldloc_S, list);
il.Emit(OpCodes.Ret);
return dm.CreateDelegate(typeof(Func<T, List<object>>)) as Func<T, List<object>>;
}
private void GetProperties()
{
if (leps == null)
leps = new List<EntityPropInfo>();
leps.Clear();
if (lgs == null)
lgs = new List<Func<T, object>>();
lgs.Clear();
foreach (var prop in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (prop.GetIndexParameters().Length > 0)
continue;
var getMethod = prop.GetGetMethod(false);
if (getMethod == null)
continue;
EntityPropInfo epi = new EntityPropInfo(prop);
leps.Add(epi);
lgs.Add(Getter(epi));
}
EntityDelegate = GetDelegate(leps);
}
private Func<T, List<object>> EntityDelegate
for (int i = 0; i < lepis.Count; ++i)
{
il.Emit(OpCodes.Ldloc, list);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, lepis[i].GetMethod);
if (lepis[i].Type.IsValueType)
{
il.Emit(OpCodes.Box, lepis[i].Type);
}
il.Emit(OpCodes.Callvirt, typeof(List<object>).GetMethod("Add"));
}