[英]C# how to implement IEnumerable for nested classes
我有一組相當簡單的只有屬性的類,例如:
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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.