c# - C#如何为嵌套类实现IEnumerable
问题描述
我有一组相当简单的类,只有属性,例如:
using System; //main data types
using System.Reflection; //to iterate through all properties of an object
using System.Collections; //for IEnumerable implementation?
namespace ConsoleApp1
{
public class WholeBase //: IEnumerable ?
{
public SomeHeaders Headers { get; set; }
public SomeBody Body { get; set; }
}
public partial class SomeHeaders
{
public string HeaderOne { get; set; }
public string HeaderTwo { get; set; }
}
public partial class InSet
{
public string AllForward { get; set; }
public string Available { get; set; }
}
public partial class SomeBody
{
public InSet MySet { get; internal set; }
public Boolean CombinedServiceIndicator { get; set; }
public int FrequencyPerDay { get; set; }
public string ValidUntil { get; set; }
}
我试图获取所有属性和值,但似乎我被卡住了,因为 IEnumerable 或缺少某些东西。这是我迄今为止尝试过的:填充属性并尝试遍历所有属性和值,但是,不起作用......
public class Program
{
//...
public static void Main(string[] args)
{
WholeBase NewThing = new WholeBase();
NewThing.Headers = new SomeHeaders { HeaderOne = "First", HeaderTwo = "Second" };
NewThing.Body = new SomeBody
{
MySet = new InSet { AllForward = "YES", Available = "YES"},
CombinedServiceIndicator = false,
FrequencyPerDay = 10,
ValidUntil = "2019-12-31"
};
void SeeThrough(WholeBase myBase)
{
//iterate through all the properties of NewThing
foreach (var element in myBase)
{
foreach (PropertyInfo prop in myBase.GetType().GetProperties())
{
var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
Console.WriteLine(prop.GetValue(element, null).ToString());
}
}
};
}
}
解决方案
好吧,您似乎在想“嗯,我将遍历类 'A' 的所有属性值,同时使用反射来获取类 'A' 的所有属性,然后对于每个属性,我将显示其值。”
这里有很多问题。
首先 - 循环所有值只能使用实现接口的对象,IEnumerable
但您并不真正需要它。由于您使用反射获取其所有属性,因此您也可以使用它来获取值:
foreach (PropertyInfo prop in myBase.GetType().GetProperties())
{
// this returns object
var element = prop.GetValue(myBase, null);
Console.WriteLine(element);
}
其次 -ToString()
不知道如何显示对象的字段,除非对象覆盖它。
虽然上面的代码可以编译和工作,但是因为 element 是一个对象而不是原始类型,除非你重写了这个方法,.ToString
这个调用Console.WriteLine
只会显示类型的名称。
您可以再次循环遍历该对象的所有属性,并最终为每个属性获取一个值:
foreach (var childProperty in element.GetType().GetProperties())
{
Console.WriteLine(childProperty.GetValue(element, null).ToString());
}
推荐阅读
- css - 确保在 Google pagespeed 洞察报告中未解决 webfont 加载期间文本保持可见
- inner-join - 使用 FOR ALL ENTRIES 连接各种表
- drupal - 如何更改临时 URL - RHEL 和 Drupal 7
- java - 如何使用 danielwegener Kafka appender 在 Kafka 消息中自定义 ZonedDateatime
- javascript - 使用离子(角度)。无法访问在显示屏/屏幕内有按钮的移动设备的硬件后退按钮
- swift - 如何使用以下示例修改gridView
- ios - 在 IOS 中使用 MucSub 获取 MUC 消息历史记录
- python - 使用 python 和 oracle db 在文件中获取、分离和写入相应数据的最快方法
- c++ - 堆栈变量的地址不断变化
- string - 在 kdb+ 中设置带有整数变量和字符串的保存路径的问题