【发布时间】:2019-12-18 12:31:29
【问题描述】:
我有一组相当简单的类,只有属性,例如:
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());
}
}
};
}
}
【问题讨论】:
-
您的类不需要实现
IEnumerable即可获取其所有属性。你目前的方法有什么问题?你有什么错误吗? -
你不需要两个循环。一个单一的就足够了(顺便说一下,内部的)
-
要使用 IEnumerable,您需要多个项目。看起来您的所有属性都是单例。如果可能的话,最简单的方法就是将项目设置为数组或列表。
-
@jdweng 非常感谢您的建议,我是新手,不知道如何使用嵌套对象实现列表,特别是
public class WholeBase示例.. -
你需要一个变量: List
WholeBase = new List ();然后将项目添加到列表中。
标签: c#