Bud*_*Joe 12 .net c# reflection properties metaprogramming
在C#中解决这个问题的最佳方法是什么?
string propPath = "ShippingInfo.Address.Street";
Run Code Online (Sandbox Code Playgroud)
我将有一个属性路径,如上面从映射文件中读取的那个.我需要能够向Order对象询问下面代码的值是什么.
this.ShippingInfo.Address.Street
Run Code Online (Sandbox Code Playgroud)
平衡性能与优雅.所有对象图关系应该是一对一的.第2部分:如果它的List <>或类似的东西,添加它的能力有多难以获取第一个.
Luk*_*keH 25
也许是这样的?
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);
Run Code Online (Sandbox Code Playgroud)
或者,如果你更喜欢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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4772 次 |
| 最近记录: |