gpt4 book ai didi

C# - 递归/反射属性值

转载 作者:可可西里 更新时间:2023-11-01 08:17:53 26 4
gpt4 key购买 nike

在 C# 中执行此操作的最佳方法是什么?

string propPath = "ShippingInfo.Address.Street";

我将有一个属性路径,就像上面从映射文件中读取的那样。我需要能够询问 Order 对象下面代码的值是什么。

this.ShippingInfo.Address.Street 

平衡性能与优雅。所有对象图关系都应该是一对一的。第 2 部分:如果它是 List<> 或类似的东西,添加它获取第一个的能力有多难。

最佳答案

也许是这样的?

string propPath = "ShippingInfo.Address.Street";

object propValue = this;
foreach (string propName in propPath.Split('.'))
{
PropertyInfo propInfo = propValue.GetType().GetProperty(propName);
propValue = propInfo.GetValue(propValue, null);
}

Console.WriteLine("The value of " + propPath + " is: " + propValue);

或者,如果您更喜欢 LINQ,则可以试试这个。 (尽管我个人更喜欢非 LINQ 版本。)

string propPath = "ShippingInfo.Address.Street";

object propValue = propPath.Split('.').Aggregate(
(object)this,
(value, name) => value.GetType().GetProperty(name).GetValue(value, null));

Console.WriteLine("The value of " + propPath + " is: " + propValue);

关于C# - 递归/反射属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2692807/

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