gpt4 book ai didi

c# - 在 C# 中获取嵌套对象字段的完整路径

转载 作者:太空宇宙 更新时间:2023-11-03 18:52:25 25 4
gpt4 key购买 nike

假设我们有两个类:

public class MyClass
{
public MyClass2 Foo { get; set; }
}

public class MyClass2
{
public int Blah { get; set; }
}

我想显示 Blah 属性的完整路径但不包括 namespace ,因此在这种情况下,预期结果将是:

MyClass.Foo.Blah

我已经在 Debug模式下运行了这些东西,并使用反射 typeof(MyClass)MyClass 对象中进行了 dag。最后,我使用以下表达式在树中找到了 Blah 属性:

((System.Reflection.PropertyInfo[])((System.Reflection.TypeInfo)((System.Reflection.RuntimeMethodInfo)((System.Reflection.MemberInfo[])((System.Reflection.TypeInfo)((System.Reflection.RuntimeFieldInfo)((System.Reflection.FieldInfo[])((System.Reflection.TypeInfo)typeof(MyClass)).DeclaredFields)[0]).DeclaringType).DeclaredMembers)[0]).ReturnType).DeclaredProperties)[0]

看起来有点笨拙。任何人都知道一些“聪明”的方式如何在不对字段名称进行硬编码的情况下接收结果?干杯

最佳答案

您可以使用表达式的 ToString 方法来获取路径。需要进行最小的修改以将 lambda 部分 (x => x) 替换为 YourClassName:

usage: ReflectionHelper<MyClass>.GetPath(x => x.Foo.Blah) // -> "MyClass.Foo.Blah"

public class ReflectionHelper<T>
{
public static string GetPath<TProperty>(Expression<Func<T, TProperty>> expr)
{
var name = expr.Parameters[0].Name;

return expr.ToString()
.Replace($"{name} => {name}", typeof(T).Name);
}
}

关于c# - 在 C# 中获取嵌套对象字段的完整路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54082293/

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