当前位置: 代码迷 >> 综合 >> 使用反射,动态创建类,然后调用泛型,完成其它工作
  详细解决方案

使用反射,动态创建类,然后调用泛型,完成其它工作

热度:82   发布时间:2023-10-14 21:45:09.0

主要完成,将对象与对象动态映射。

一,先定义类型。

    public class Example{public string Id { get; set; }public string Name { get; set; }public int Age { get; set; }public DateTime createtime { get; set; }public Example Init(){Example sdt = new Example { Id = "3", Name = "3abc", Age = 310, createtime = DateTime.Now };return sdt;}}

二,使用反射,动态创建类

            //创建编译器实例CSharpCodeProvider provider = new CSharpCodeProvider();//设置编译参数CompilerParameters paras = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true };//创建动态代码StringBuilder classSource = new StringBuilder();classSource.Append("public class DynamicClass \n");classSource.Append("{\n");classSource.Append(" public int Id { set; get; }  \n");classSource.Append(" public string Name { set; get; }  \n");classSource.Append(" public int Age { set; get; }  \n");classSource.Append(" public string context { set; get; }  \n");classSource.Append("}");Console.WriteLine(classSource.ToString());//编译代码 CompilerResults result = provider.CompileAssemblyFromSource(paras, classSource.ToString());//获取编译后的程序集Assembly assembly = result.CompiledAssembly;object obclass = assembly.CreateInstance("DynamicClass");Type dynamicType = obclass.GetType();var newObject = Activator.CreateInstance(dynamicType);

三,创建,类中的泛型方法,泛型类中方法,静态类中泛型方法,静态泛型类中方法。

四,调用上面四种方法

            //这是调用类中泛型方法var type0 = typeof(Mapper0);var a_Context0 = Activator.CreateInstance(type0);type0.GetMethod("MapTo").MakeGenericMethod(sdt.GetType(), dynamicType).Invoke(a_Context0, new object[] { sdt });//这是调用泛型类中方法var type1 = typeof(Mapper1<>).MakeGenericType(sdt.GetType());var a_Context1 = Activator.CreateInstance(type1);var ddd1= type1.GetMethod("MapTo").Invoke(a_Context1, new object[] { sdt });//也可以用动态方式调用dynamic a_Context11 = Activator.CreateInstance(type1);var ddd11 = a_Context11.MapTo(sdt);//这是调用静态类中的泛型方法var type2 = typeof(Mapper2);type2.GetMethod("MapTo").MakeGenericMethod(sdt.GetType(), dynamicType).Invoke(null, new object[] { sdt });//这是调用静态泛型类中的方法var type3 = typeof(Mapper3<>).MakeGenericType(sdt.GetType());type3.GetMethod("MapTo").Invoke(null, new object[] { sdt });//如果是扩展类,调用没有成功返回,但在类多写一个不是扩展的方法就能实现

 

  相关解决方案