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 }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM