首页 / C# / C# – 从子类中获取属性值
C# – 从子类中获取属性值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C# – 从子类中获取属性值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2265字,纯文字阅读大概需要4分钟。
内容图文
![C# – 从子类中获取属性值](/upload/InfoBanner/zyjiaocheng/825/ac66d929945d4db0b723605ed23454b3.jpg)
我在运行时使用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;
}
}
我将Property Name作为参数:fieldName传递给此方法.
现在,我需要在运行时从上面的类的子对象访问属性值.
那里的任何人都可以指导我如何访问子对象属性值?
解决方法:
由于您希望能够在任意嵌套的子对象上查找对象,因此您需要一个可以递归调用的函数.这很复杂,因为您可能有孩子会回顾他们的父母,因此您需要跟踪您在搜索中看到过的对象.
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# – 从子类中获取属性值全部内容,希望文章能够帮你解决C# – 从子类中获取属性值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。