C#如何为嵌套类实现IEnumerable
我有一组相当简单的类,它们只具有属性,例如:C#如何为嵌套类实现IEnumerable,c#,C#,我有一组相当简单的类,它们只具有属性,例如: 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
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()
不知道如何显示对象的字段,除非对象重写它
虽然上面的代码将编译并工作,但因为元素是对象而不是基元类型,除非您重写了方法。ToString
此调用控制台。WriteLine
将只显示类型的名称
您可以再次循环此对象的所有属性,并最终获得每个属性的值:
foreach (var childProperty in element.GetType().GetProperties())
{
Console.WriteLine(childProperty.GetValue(element, null).ToString());
}
您的类不需要实现
IEnumerable
,就可以获得其所有属性。你对目前的方法有何看法?你有错误吗?你不需要两个循环。简单的一个就足够了(顺便说一下,内部的一个)使用IEnumerable,因为您需要多个项目。看起来您的所有属性都是单例。如果可能的话,最简单的方法就是制作项目数组或列表。@jdweng非常感谢您的建议,我是新手,不知道如何使用嵌套对象实现列表,特别是使用公共类WholeBase
例如..您需要一个变量:List WholeBase=new List();然后将项目添加到列表中。@HimBromBeere是的,我把smth弄糊涂了。感谢you@Fabjan是的,你猜到了我的意图,非常感谢你的代码,它非常有用,我就快到了。我想将两者结合起来,有点像:Console.WriteLine(element+“=”+childProperty.GetValue(element.ToString())
但是很明显,以这种方式元素,null
必须更改,是吗?