標籤: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(裝載程式集):