C#类的属性遍历及属性值获取
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)題。
- 上一篇: 解决 dockerfile 构建镜像报错
- 下一篇: c# char unsigned_dll