c# - 如何递归地和反射地获取所有可能的字段名称路径的列表?
问题描述
我正在尝试获取一个字符串集合,该集合为我提供了所有班级成员的字段名称,以.
s 分隔。例如:
public class Apple
{
public Banana MyBanana = new Banana();
public Cranberry MyCranberry = new Cranberry();
}
public class Banana
{
public int MyNumber = 5;
public Cranberry MyCranberry = new Cranberry();
}
public class Cranberry
{
public string MyString = "Hello!";
public int MyOtherNumber = 10;
}
public class Demo
{
public List<string> GetFields(Type Apple)
{
//I can't figure this out
//But it should return a list with these elements:
var result = new List<string>
{
"MyBanana.MyNumber",
"MyBanana.MyCranberry.MyString",
"MyBanana.MyCranberry.MyOtherNumber",
"MyCranberry.MyString",
"MyCranberry.MyOtherNumber"
};
return result;
}
}
我相信需要某种递归和反射,但是在编写了几个小时功能失调的代码之后,我需要一些帮助。
我需要这个的原因是因为我正在访问使用这些文件路径作为它们各自值的键的第三方代码。
一次失败尝试的示例:
private List<string> GetFields(Type type)
{
var results = new List<string>();
var fields = type.GetFields();
foreach (var field in fields)
{
string fieldName = field.Name;
if (field.ReflectedType.IsValueType)
{
results.Add(fieldName);
}
else
{
results.Add(field.Name + GetFields(field.FieldType));
}
}
return results;
}
我发现了几个相关的问题,但没有一个完全符合我的问题,而且我自己也无法跳出: Recursively Get Properties & Child Properties Of A Class,https://stackoverflow.c “om/questions/6196413/ how-to-recursively-print-the-values-of-an-objects-properties-using-reflection, Recursively Get Properties & Child Properties Of An Object , .NET, C#, Reflection: 列出一个字段的字段,它本身, 有字段
解决方案
您需要一个递归实现:
HashSet<Type> nonRecursiveTypes = new HashSet<Type> { typeof(System.Int32), typeof(System.String) }; // add other simple types here
IEnumerable<string> GetFields(object obj)
{
foreach (var field in obj.GetType().GetFields())
{
if (nonRecursiveTypes.Contains(field.FieldType))
yield return field.Name;
else
foreach (var innerFieldName in GetFields(field.GetValue(obj)))
yield return field.Name + "." + innerFieldName;
}
}
推荐阅读
- python - 获取页面源作为浏览器在 Selenium 中显示
- typescript - 在类成员和方法中扩展泛型类型
- python - 如何跳过/删除行直到某个字符串
- opencv - 使用 CUDA 构建 OpenCV 失败
- amazon-web-services - 如何授权远程用户将角色传递给 SAM lambda 部署中生成的角色?
- python - Python:在函数内使用列表进行迭代
- amazon-web-services - 何时使用 Cloud Formation 以及何时使用 EC2 实例
- flutter - 使用 rFlutter_alert 时图像未显示在 Flutter App 中
- python - Python并发不是并发的
- python - Pytest:为未参数化的测试提供 id