首页 > 代码库 > 解决夸dll返回dynamic无法访问
解决夸dll返回dynamic无法访问
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 = http://www.mamicode.com/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 = http://www.mamicode.com/new
{
str_Title = "获取标题",
str_Code = "获取标题",
dt_SheetTable = datatable
}.ToPublic();
解决夸dll返回dynamic无法访问
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。