如何循环对象的属性并获取属性的值.
我有一个对象,有几个属性填充数据.用户通过提供属性的名称来指定他想要查看的属性,我需要在对象中搜索属性并将其值返回给用户.
我怎样才能实现这一目标?
我写了下面的代码来获取属性但无法获得该prop的值:
public object FindObject(object OBJ, string PropName)
{
PropertyInfo[] pi = OBJ.GetType().GetProperties();
for (int i = 0; i < pi.Length; i++)
{
if (pi[i].PropertyType.Name.Contains(PropName))
return pi[i];//pi[i] is the property the user is searching for,
// how can i get its value?
}
return new object();
}
Run Code Online (Sandbox Code Playgroud)
试试这个(代码插入内联):
public object FindObject(object OBJ, string PropName)
{
PropertyInfo[] pi = OBJ.GetType().GetProperties();
for (int i = 0; i < pi.Length; i++)
{
if (pi[i].PropertyType.Name.Contains(PropName))
{
if (pi[i].CanRead) //Check that you can read it first
return pi[i].GetValue(OBJ, null); //Get the value of the property
}
}
return new object();
}
Run Code Online (Sandbox Code Playgroud)
要从a中获取价值PropertyInfo,请致电GetValue:)我怀疑您是否真的希望得到属性类型的名称.我怀疑你想要:
if (pi[i].Name == PropName)
{
return pi[i].GetValue(OBJ, null);
}
Run Code Online (Sandbox Code Playgroud)
请注意,您应该确保该属性不是索引器,并且可读且可访问等.LINQ是一种过滤事物的好方法,或者您可以直接使用Type.GetProperty具有所需名称的属性,而不是循环 - 然后执行所需的所有验证.
您还应该考虑遵循命名约定并使用foreach循环.哦,如果找不到属性,我可能会返回null或抛出异常.我看不出如何返回一个新的空对象是个好主意.