public static class DynamicFactory
{
//创建线程安全(对象不会再同一时刻被多个线程访问)的字典对象
private static ConcurrentDictionary<Type, Type> s_dynamicTypes = new ConcurrentDictionary<Type, Type>();
private static Func<Type, Type> s_dynamicTypeCreator = new Func<Type, Type>(CreateDynamicType);
/// <summary>
/// 创建object的扩展方法用来扩展匿名对象
/// </summary>
public static object ToPublic(this object entity)
{
try
{
var entityType = entity.GetType();
var dynamicType = s_dynamicTypes.GetOrAdd(entityType, s_dynamicTypeCreator);
var dynamicObject = Activator.CreateInstance(dynamicType);
foreach (var entityProperty in entityType.GetProperties())
{
var value = entityProperty.GetValue(entity, null);
//重新给传递过来的匿名类赋值
dynamicType.GetField(entityProperty.Name).SetValue(dynamicObject, value);
}
return dynamicObject;
}
catch (Exception ex)
{
Common.WriteLog("ToPublic", ex.ToString());
return null;
}
}
private static Type CreateDynamicType(Type entityType)
{
//创建程序集名称
try
{
var asmName = new AssemblyName("DynamicAssembly_" + Guid.NewGuid());
//定义程序集
var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
//在程序集中定义模块
var moduleBuilder = asmBuilder.DefineDynamicModule("DynamicModule_" + Guid.NewGuid());
//将传递过来的匿名类型名称重新命名并设置到新的模块程序集中
var typeBuilder = moduleBuilder.DefineType(
entityType.GetType() + "$DynamicType",
TypeAttributes.Public);
//定义该类的构造函数
typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);
//循环匿名类中所有字段
foreach (var entityProperty in entityType.GetProperties())
{
//将匿名类的字段重新定义到当前自定义的程序集中
typeBuilder.DefineField(entityProperty.Name, entityProperty.PropertyType, FieldAttributes.Public);
}
//创建自定义程序集
return typeBuilder.CreateType();
}
catch (Exception ex)
{
Common.WriteLog("ToPublic", ex.ToString());
return null;
}
}
}
//用法
dynamic excelData = new
{
str_Title = "获取标题",
str_Code = "获取标题",
dt_SheetTable = datatable
}.ToPublic();