获取指定对象的对象的属性及值 private void btnClassInfo_Click(object sender, EventArgs e)
{ Item itemtest = new Item(); itemtest.AfterSaleId = 12;
itemtest.ApproveStatus = "ApproveStatus"; SetObjPropValueToCtrls(itemtest);
} //显示对象的属性及值
private void SetObjPropValueToCtrls(object objprop)
{
foreach (System.Reflection.PropertyInfo info in typeof(Item).GetProperties()) //1、正常运行
//foreach (System.Reflection.PropertyInfo info in typeof(objprop.GetType().ToString()).GetProperties()) //2、编译不通过
{ rtbProperty.Text = rtbProperty.Text + "Name: " + info.Name +
" ; Value: " + info.GetValue(objprop, null) +
" ; Type: " + info.GetType().ToString() + "\n"; //3、Type类型全部为:System.Reflection.RuntimePropertyInfo
}
}
我查询了一下:C# typeof() 和 GetType()区别。1、typeof(x)中的x,必须是具体的类名、类型名称等,不可以是变量名称。
2、GetType()方法继承自Object,所以C#中任何对象都具有GetType()方法,它的作用和typeof()相同,返回Type类型的当前对象的类型。 比如有这样一个变量i:
Int32 i = new Int32(); i.GetType()返回值是Int32的类型,但是无法使用typeof(i),因为i是一个变量,如果要使用typeof(),则只能:typeof(Int32),返回的同样是Int32的类型。
很明显上面的写法是不对的,但是不知道怎么改正!
{ Item itemtest = new Item(); itemtest.AfterSaleId = 12;
itemtest.ApproveStatus = "ApproveStatus"; SetObjPropValueToCtrls(itemtest);
} //显示对象的属性及值
private void SetObjPropValueToCtrls(object objprop)
{
foreach (System.Reflection.PropertyInfo info in typeof(Item).GetProperties()) //1、正常运行
//foreach (System.Reflection.PropertyInfo info in typeof(objprop.GetType().ToString()).GetProperties()) //2、编译不通过
{ rtbProperty.Text = rtbProperty.Text + "Name: " + info.Name +
" ; Value: " + info.GetValue(objprop, null) +
" ; Type: " + info.GetType().ToString() + "\n"; //3、Type类型全部为:System.Reflection.RuntimePropertyInfo
}
}
我查询了一下:C# typeof() 和 GetType()区别。1、typeof(x)中的x,必须是具体的类名、类型名称等,不可以是变量名称。
2、GetType()方法继承自Object,所以C#中任何对象都具有GetType()方法,它的作用和typeof()相同,返回Type类型的当前对象的类型。 比如有这样一个变量i:
Int32 i = new Int32(); i.GetType()返回值是Int32的类型,但是无法使用typeof(i),因为i是一个变量,如果要使用typeof(),则只能:typeof(Int32),返回的同样是Int32的类型。
很明显上面的写法是不对的,但是不知道怎么改正!
===》
foreach (System.Reflection.PropertyInfo info in typeof(objprop).GetProperties())
{ Item itemtest = new Item(); itemtest.AfterSaleId = 12;
itemtest.ApproveStatus = "ApproveStatus";
}//显示对象的属性及值
private void SetObjPropValueToCtrls(object objprop)
{ System.Type type = objprop.GetType();
foreach (System.Reflection.PropertyInfo p in type.GetProperties())
{
rtbProperty.Text = rtbProperty.Text + "Name: " + p.Name +
" Value:" + p.GetValue(objprop, null) +
" PropertyType: " + p.PropertyType +
"\n";
}
}