.net 取得类的属性、方法、成员及通过属性名取得属性值
//自定义的类 model m = new model(); //取得类的Type实例 //Type t = typeof(model); //取得m的Type实例 Type t = m.GetType(); string className = t.Name +"\r\n"; //获取所有方法 System.Reflection.MethodInfo[] methods = t.GetMethods(); //获取所有成员 System.Reflection.MemberInfo[] members = t.GetMembers(); //获取所有属性 System.Reflection.PropertyInfo[] properties = t.GetProperties(); //取得类的属性名并获取属性值 foreach (System.Reflection.PropertyInfo s in t.GetProperties()) { className += s.Name + ":" + m.GetType().GetProperty(s.Name).GetValue(m, null).ToString() + "\r\n"; }
IEnumerable的几个简单用法:
public static void Print(IEnumerable myList) { int i = 0; foreach (Object obj in myList) { if (obj is Student)//这个是类型的判断,这里Student是一个类或结构 { Student s=(Student)obj; Console.WriteLine("\t[{0}]:\t{1}", i++, s.Sname); } if (obj is int) { Console.WriteLine("INT:{0}",obj); } } Console.WriteLine(); }