Helpers.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace AopCache.Core.Common
{
///
/// 对象转换成字典
///
public clast Helpers
{
#region Dictionary
private static readonly ConcurrentDictionary DictionaryCache =
new ConcurrentDictionary();
public static Dictionary ToDictionary(object obj)
{
var type = obj.GetType();
if (!DictionaryCache.TryGetValue(type, out Func getter))
{
getter = CreateDictionaryGenerator(type);
DictionaryCache.TryAdd(type, getter);
}
return getter(obj);
}
private static Func CreateDictionaryGenerator(Type type)
{
var dm = new DynamicMethod($"Dictionary{Guid.NewGuid()}", typeof(Dictionary), new[] { typeof(object) }, type, true);
ILGenerator il = dm.GetILGenerator();
il.DeclareLocal(typeof(Dictionary));
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Newobj, typeof(Dictionary).GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Stloc_0);
foreach (var item in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
string columnName = item.Name;
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldstr, columnName);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, item.GetGetMethod());
if (item.PropertyType.IsValueType)
{
il.Emit(OpCodes.Box, item.PropertyType);
}
il.Emit(OpCodes.Callvirt, typeof(Dictionary).GetMethod("Add"));
}
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ret);
return (Func)dm.CreateDelegate(typeof(Func));
}
#endregion
#region List
///
/// 把list按照指定数量分隔
///
///
///
///
///
public static List SplitList(List list, int length)
{
if (list == null || list.Count