我有一个对象的ArrayList,我试图使用反射来获取ArrayList中每个对象的每个属性的名称。例如:
private class TestClass
{
private int m_IntProp;
private string m_StrProp;
public string StrProp
{
get
{
return m_StrProp;
}
set
{
m_StrProp = value;
}
}
public int IntProp
{
get
{
return m_IntProp;
}
set
{
m_IntProp = value;
}
}
}
ArrayList al = new ArrayList();
TestClass tc1 = new TestClass();
TestClass tc2 = new TestClass();
tc1.IntProp = 5;
tc1.StrProp = "Test 1";
tc2.IntProp = 10;
tc2.StrPRop = "Test 2";
al.Add(tc1);
al.Add(tc2);
foreach (object obj in al)
{
// Here is where I need help
// I need to be able to read the properties
// StrProp and IntProp. Keep in mind that
// this ArrayList may not always contain
// TestClass objects. It can be any object,
// which is why I think I need to use reflection.
}
答案 0 :(得分:7)
foreach (object obj in al)
{
foreach(PropertyInfo prop in obj.GetType().GetProperties(
BindingFlags.Public | BindingFlags.Instance))
{
object value = prop.GetValue(obj, null);
string name = prop.Name;
// ^^^^ use those
}
}
答案 1 :(得分:1)
您可以使用as
运算符,这样就不必使用Reflection。
foreach(object obj in al)
{
var testClass = obj as TestClass;
if (testClass != null)
{
//Do stuff
}
}
答案 2 :(得分:0)
这很简单:
PropertyInfo[] props = obj.GetType().GetProperties();
GetType方法将返回实际类型,而不是object
。每个PropertyInfo
对象都有一个Name属性。