cnblogs/dcrenl/.net 取得类的属性、方法、成员及通过属性名取得属性值.html
2024-09-24 12:43:01 +08:00

25 lines
1014 B
HTML

<div>//自定义的类</div>
<div>model m = new model();</div>
<div>&nbsp;</div>
<div>//取得类的Type实例</div>
<div>//Type t = typeof(model);&nbsp;</div>
<div>&nbsp;</div>
<div>//取得m的Type实例</div>
<div>Type t = m.GetType();&nbsp;</div>
<div>&nbsp;</div>
<div>string className = t.Name +"\r\n";&nbsp;</div>
<div>&nbsp;</div>
<div>//获取所有方法&nbsp;</div>
<div>System.Reflection.MethodInfo[] methods = t.GetMethods();&nbsp;</div>
<div>&nbsp;</div>
<div>//获取所有成员</div>
<div>System.Reflection.MemberInfo[] members = t.GetMembers();&nbsp;</div>
<div>&nbsp;</div>
<div>//获取所有属性&nbsp;</div>
<div>System.Reflection.PropertyInfo[] properties = t.GetProperties();&nbsp;</div>
<div>&nbsp;</div>
<div>//取得类的属性名并获取属性值</div>
<div>foreach (System.Reflection.PropertyInfo s in t.GetProperties())</div>
<div>{</div>
<div>&nbsp; &nbsp; className &nbsp;+= s.Name + ":" + m.GetType().GetProperty(s.Name).GetValue(m, null).ToString() + "\r\n";</div>
<div>}</div>