日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > C# >内容正文

C#

C#类的属性遍历及属性值获取

發(fā)布時(shí)間:2023/12/18 C# 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C#类的属性遍历及属性值获取 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1、定義一個(gè)類

public class Person {public string Name { get; set; }public int ID { get; set; } }

2、獲取屬性

方法一、定義一個(gè)類的對(duì)象獲取

Person p = new Person(); foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties()) {Console.WriteLine(info.Name); }

方法二、通過(guò)類獲取

var properties = typeof(Person).GetProperties(); foreach (System.Reflection.PropertyInfo info in properties) {Console.WriteLine(info.Name); }

3、通過(guò)屬性名獲取對(duì)象屬性值

p.Name = "張三"; var name = p.GetType().GetProperty("Name").GetValue(p, null); Console.WriteLine(name);

4、完整代碼及結(jié)果顯示

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("通過(guò)屬性值獲取屬性:");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;//獲得屬性的名字,后面就可以根據(jù)名字判斷來(lái)進(jìn)行些自己想要的操作
//獲得屬性的類型,進(jìn)行判斷然后進(jìn)行以后的操作,例如判斷獲得的屬性是整數(shù)
if(value1.GetType() == typeof(int))
{
//進(jìn)行你想要的操作
}
}
public int Pid
{
get { return pid; }
set { pid = value; }
}

?

?

//****************

? public void InitialProperty()//初始化設(shè)定
? ? ? ? {
? ? ? ? ? ? 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);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ?

? ? ? ? ? ? }
? ? ? ? ? ?

? ? ? ? }

總結(jié)

以上是生活随笔為你收集整理的C#类的属性遍历及属性值获取的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。