C#中 反射中的Assembly(装载程序集):

反射中的Assembly(装载程序集):可以通过Assembly的信息来获取程序的类,实例等编程需要用到的信息。

1  String assemblyName = @"NamespaceRef";//命名空间
2     String strongClassName = @"NamespaceRef.China";//需要动态生成的类交China

 Assembly.Load(assemblyName).CreateInstance(strongClassName); 

反射用法:利用GetType()动态取实体属性:
GetType():获取当前实例的System.Type.
 1 现在有两个类:Student 和 StudentDTO如下:
 2     public class Student
 3     {
 4         public Student()
 5         { 
 6         
 7         }
 8 
 9         public virtual string Id { get; set; }
10 
11         public virtual string StudentNo { get; set; }
12 
13         public virtual string Name { get; set; }
14 
15     }
 1 public class StudentDTO
 2     {
 3        public StudentDTO()
 4        { 
 5 
 6        }
 7        public virtual string Id { get; set; }
 8 
 9        public virtual string StudentNo { get; set; }
10 
11        public virtual string Name { get; set; }
12 
13        public virtual string ClassId { get; set; }
14 
15      。。。
16     }
 1 使用GetType()实现实体属性之间赋值:
 2             foreach (var item in student.GetType().GetProperties())    //返回Student的所有公共属性
 3             {
 4                 var value = item.GetValue(student, null);   //返回属性值    
 5                 var setobj = studentDTO.GetType().GetProperty(item.Name);   //搜索具有指定属性名称的公共属性
 6                 if (value != null && setobj != null)
 7                 {
 8                     setobj.SetValue(studentDTO, value, null);
 9                 }
10             } 
 1 技巧:把方法的参数设置成object类型,就可以一个方法处理多个类型的数据,如下:
 2 public void TypeDemo(object parameter)
 3 {
 4     if(parameter.GetType() == typeof(OtherClass))
 5         {
 6             ....
 7         }
 8  if(parameter.GetType() == typeof(OtherClass1))
 9         {
10             ....
11         }
12  if(parameter.GetType() == typeof(OtherClass2))
13         {
14             ....
15         }
16         ..........
17 }
 
原文地址:https://www.cnblogs.com/xiaoliangge/p/6005989.html