我在运行时使用 C# 中的反射访问类对象的属性值。
public bool GetValue(string fieldName, out object fieldValue)
{
// Get type of current record
Type curentRecordType = _currentObject.GetType();
PropertyInfo property = curentRecordType.GetProperty(fieldName);
if (property != null)
{
fieldValue = property.GetValue(_currentObject, null).ToString();
return true;
}
else
{
fieldValue = null;
return false;
}
}
我将属性名称作为参数传递给此方法:fieldName。
现在,我需要在运行时访问上述类的子对象的属性值。
那里的任何人都可以指导我如何访问子对象属性值吗?
最佳答案
由于您希望能够在任意嵌套的子对象上找到对象,因此您需要一个可以递归调用的函数。由于您的 child 可能会回头引用他们的 parent ,所以这很复杂,因此您需要跟踪您之前在搜索中看到的对象。
static bool GetValue(object currentObject, string propName, out object value)
{
// call helper function that keeps track of which objects we've seen before
return GetValue(currentObject, propName, out value, new HashSet<object>());
}
static bool GetValue(object currentObject, string propName, out object value,
HashSet<object> searchedObjects)
{
PropertyInfo propInfo = currentObject.GetType().GetProperty(propName);
if (propInfo != null)
{
value = propInfo.GetValue(currentObject, null);
return true;
}
// search child properties
foreach (PropertyInfo propInfo2 in currentObject.GetType().GetProperties())
{ // ignore indexed properties
if (propInfo2.GetIndexParameters().Length == 0)
{
object newObject = propInfo2.GetValue(currentObject, null);
if (newObject != null && searchedObjects.Add(newObject) &&
GetValue(newObject, propName, out value, searchedObjects))
return true;
}
}
// property not found here
value = null;
return false;
}
如果您知道您的属性在哪个子对象中,您可以直接将路径传递给它,如下所示:
public bool GetValue(string pathName, out object fieldValue)
{
object currentObject = _currentObject;
string[] fieldNames = pathName.Split(".");
foreach (string fieldName in fieldNames)
{
// Get type of current record
Type curentRecordType = currentObject.GetType();
PropertyInfo property = curentRecordType.GetProperty(fieldName);
if (property != null)
{
currentObject = property.GetValue(currentObject, null).ToString();
}
else
{
fieldValue = null;
return false;
}
}
fieldValue = currentObject;
return true;
}
而不是像GetValue("foo", out val)
那样调用它你会这样调用它 GetValue("foo.bar", out val)
.
关于C# - 从子类中获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4075244/