C# 在类中反射

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace WindowsFormsApplication1  
  6. {  
  7. public class Contract  
  8.     {  
  9. public string employeename { get; set; }  
  10.     }  
  11. }  
  12. 1.遍历属性和属性值

 

  1. C#代码  
  2. public void EachProperties()  
  3.        {  
  4.            Contract contract = new Contract { employeename = "Rikas" };  
  5.            Type type = contract.GetType();  
  6.            System.Reflection.PropertyInfo[] ps = type.GetProperties();  
  7. foreach (PropertyInfo i in ps)  
  8.            {  
  9. object obj = i.GetValue(contract, null);  
  10. string name = i.Name;  
  11.            }  
  12.        }  
  13. 2.然还有判断属性类型的,我没有找到更好的方法判断一个累中的属性的类型是不是另一个类,如果有其他方法欢迎评论
  14. C#代码  
  15. public void EachProperties()  
  16.         {  
  17.             Contract contract = new Contract { employeename = "Rikas" };  
  18.             Type type = contract.GetType();  
  19.             System.Reflection.PropertyInfo[] ps = type.GetProperties();  
  20. foreach (PropertyInfo i in ps)  
  21.             {  
  22. if (i.PropertyType == typeof(string))//属性的类型判断  
  23.                 {  
  24. object obj = i.GetValue(contract, null);  
  25. string name = i.Name;  
  26.                 }  
  27.             }  
  28.         }  
原文地址:https://www.cnblogs.com/louby/p/6077359.html