比方說,我有一個像這樣的Print方法:
private static void Print(IEnumerable items)
{
// Print logic here
}
我想將一個集合類傳遞給這個Print方法,該方法應該像表格一樣打印所有字段。例如,我的輸入集合可以是“人員”或“訂單”或“汽車”等。
如果我將“Cars”集合傳遞給Print方法,它應該打印“Car”詳細信息列表,例如:Make,Color,Price,Class等。
直到運行時我才知道集合的類型。我嘗試使用TypeDescriptors
和PropertyDescriptorCollection
實現了一個解決方案。但是,我覺得這不是一個好的解決方案。有沒有其他方法可以使用表達式或泛型來實現這一點?
您可以像這樣實現Print:
static void Print<T>(IEnumerable<T> items)
{
var props = typeof(T).GetProperties();
foreach (var prop in props)
{
Console.Write("{0}\t", prop.Name);
}
Console.WriteLine();
foreach (var item in items)
{
foreach (var prop in props)
{
Console.Write("{0}\t", prop.GetValue(item, null));
}
Console.WriteLine();
}
}
它只是循環遍歷類的每個屬性以打印屬性的名稱,然後打印每個項目,並為每個項目打印屬性的值。
我認為你應該在這裡使用泛型(而不是其他答案中的建議);您希望集合中的項目是單一類型,以便您可以打印表頭。
對於表格格式,您可以檢查此問題的答案。