C#类的属性遍历及属性值获取
1、定義一個類
public class Person {public string Name { get; set; }public int ID { get; set; } }2、獲取屬性
方法一、定義一個類的對象獲取
Person p = new Person(); foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties()) {Console.WriteLine(info.Name); }方法二、通過類獲取
var properties = typeof(Person).GetProperties(); foreach (System.Reflection.PropertyInfo info in properties) {Console.WriteLine(info.Name); }3、通過屬性名獲取對象屬性值
p.Name = "張三"; var name = p.GetType().GetProperty("Name").GetValue(p, null); Console.WriteLine(name);4、完整代碼及結果顯示
var properties = typeof(Person).GetProperties(); foreach (System.Reflection.PropertyInfo info in properties) {Console.WriteLine(info.Name); } Console.WriteLine("另一種遍歷屬性的方法:");Person p = new Person(); foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties()) {Console.WriteLine(info.Name); }Console.WriteLine("通過屬性值獲取屬性:");p.Name = "張三"; var name = p.GetType().GetProperty("Name").GetValue(p, null); Console.WriteLine(name); Console.ReadLine();Type t = tc.GetType();//獲得該類的Type
//再用Type.GetProperties獲得PropertyInfo[],然后就可以用foreach 遍歷了
foreach (PropertyInfo pi in t.GetProperties
{
object value1 = pi.GetValue(tc, null));//用pi.GetValue獲得值
string name = pi.Name;//獲得屬性的名字,后面就可以根據名字判斷來進行些自己想要的操作
//獲得屬性的類型,進行判斷然后進行以后的操作,例如判斷獲得的屬性是整數
if(value1.GetType() == typeof(int))
{
//進行你想要的操作
}
}
public int Pid
{
get { return pid; }
set { pid = value; }
}
?
?
//****************
? public void InitialProperty()//初始化設定
? ? ? ? {
? ? ? ? ? ? System.Reflection.PropertyInfo[] properties = this.GetType().GetProperties();
? ? ? ? ? ? foreach(var v in properties)
? ? ? ? ? ? {
? ? ? ? ? ? ? ?string type= v.PropertyType.Name;
? ? ? ? ? ? ? ? if (type=="String")
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? v.SetValue(this,"456",null);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? else if(type=="Bitmap")
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? v.SetValue(this, new Bitmap(Image.FromFile("1.png")), null);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ?
? ? ? ? ? ? }
? ? ? ? ? ?
? ? ? ? }
總結
以上是生活随笔為你收集整理的C#类的属性遍历及属性值获取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决 dockerfile 构建镜像报错
- 下一篇: C#中5步完成word文档打印的方法