gpt4 book ai didi

c# - 获取嵌套类的属性值始终为空

转载 作者:行者123 更新时间:2023-11-30 16:47:57 25 4
gpt4 key购买 nike

我有以下两个类

public class Family
{
public string ChildName { get; set; }
}

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Family Child { get; set; }

}

我有一个 Employee 类的实例,如下所示。

 Employee employee = new Employee();
employee.Name = "Ram";
employee.Id = 77;
employee.Child = new Family() { ChildName = "Lava" };

我有一个根据属性名称获取属性值的方法,如下所示:

public static object GetPropertyValue(object src, string propName)
{
string[] nameParts = propName.Split('.');

if (nameParts.Length == 1)
{
return src.GetType().GetRuntimeProperty(propName).GetValue(src, null);
}

foreach (String part in nameParts)
{
if (src == null) { return null; }

Type type = src.GetType();

PropertyInfo info = type.GetRuntimeProperty(part);

if (info == null)
{ return null; }

src = info.GetValue(src, null);
}
return src;
}

在上面的方法中,当我尝试获取嵌套类的属性值时

GetPropertyValue(employee, "employee.Child.ChildName")  

GetPropertyValue(GetPropertyValue(employee, "Family"), "ChildName"

不返回任何值,因为 type.GetRuntimeProperty(part) 始终为 null。

有什么办法可以解决这个问题吗?

最佳答案

你的问题出在这一行:

foreach (String part in nameParts)

因为您正在遍历 nameParts 的每个部分,所以您也在遍历“employee”,这当然不是一个有效的属性。

试试这个:

foreach (String part in nameParts.Skip(1))

或者像这样调用方法:

GetPropertyValue(employee, "Child.ChildName")

(注意没有“employee.”,因为你已经传递了一个 employee)

关于c# - 获取嵌套类的属性值始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38736137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com