C#中 反射中的Assembly(裝載程式集):

來源:互聯網
上載者:User

標籤:dem   each   屬性   object   命名   tty   處理   pac   virt   

反射中的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 }

 

 

C#中 反射中的Assembly(裝載程式集):

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.