gpt4 book ai didi

c# - 如何按名称获取实体的子属性

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

在类 Person 中,我与类 Position 有关系,类 Position 与类 PositionTitle 有关系,而 PositionTitle 有一个名为 Title 的属性

public class Person
{
public Position Position{get;set;}
}

public class Position
{
public PositionTitle PositionTitle{get;set;}
}

public class PositionTitle
{
public string Title{get;set;}
}

我有一个字符串“Person.Position.PositionTitle.Title”,我怎样才能用这个字符串得到这个人的这个属性呢??

最佳答案

您需要按点拆分字符串,然后使用反射按名称获取每个属性。您可以使用 PropertyInfo.PropertyType 获取属性的类型 - 然后用它来获取链中的下一个属性。像这样:

public object GetProperty(object source, string path)
{
string[] bits = path.Split('.');
Type type = source.GetType(); // Or pass this in
object result = source;
foreach (string bit in bits)
{
PropertyInfo prop = type.GetProperty(bit);
type = prop.PropertyType;
result = prop.GetValue(result, null);
}
return result;
}

您可能希望针对绑定(bind)标志等进行调整,但这是正确的基本想法。

关于c# - 如何按名称获取实体的子属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6420883/

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