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

36 lines
1.1 KiB
HTML

<div id="sina_keyword_ad_area2" class="articalContent newfont_family">
<div>//自定义的类</div>
<div>model m = new model();</div>
<div><br />
</div>
<div>//取得类的Type实例</div>
<div>//Type t = typeof(model);&nbsp;</div>
<div><br />
</div>
<div>//取得m的Type实例</div>
<div>Type t = m.GetType();&nbsp;</div>
<div><br />
</div>
<div>string className = t.Name +"\r\n";&nbsp;</div>
<div><br />
</div>
<div>//获取所有方法&nbsp;</div>
<div>System.Reflection.MethodInfo[] methods =t.GetMethods();&nbsp;</div>
<div><br />
</div>
<div>//获取所有成员</div>
<div>System.Reflection.MemberInfo[] members =t.GetMembers();&nbsp;</div>
<div><br />
</div>
<div>//获取所有属性&nbsp;</div>
<div>System.Reflection.PropertyInfo[] properties =t.GetProperties();&nbsp;</div>
<div><br />
</div>
<div>//取得类的属性名并获取属性值</div>
<div>foreach (System.Reflection.PropertyInfo s int.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>
</div>
<p>&nbsp;</p>