[英]How to pass a list and string into a generic method which has generic list parameter
I have the following method我有以下方法
private static void WriteReport<T>(List<T> report, string reportName)
{
using (StreamWriter sw = new StreamWriter(@path)
{
for (var row = 0; row < report.Count; row++)
{
for (var column = 0; column < report.ElementAt(row).Count; column++)
sw.Write(report[row][column] + ",");
sw.WriteLine();
}
}
}
I can only pass in the above method the List<object>
as parameter but I also want to pass parameter List<List<object>>
in some cases.我只能将List<object>
作为参数传入上述方法,但在某些情况下我也想传递参数List<List<object>>
。 But I couldn't figure out the correct way to do so.但我想不出这样做的正确方法。
Edit: Cause whenever I pass List<List<object>>
only then the nested for loop can be applied but if I pass list<object>
then no nested loop can be applied and not sure how to structure my method to code it correctly编辑:因为每当我通过List<List<object>>
时,才可以应用嵌套的 for 循环,但是如果我通过list<object>
则不能应用嵌套循环,并且不确定如何构造我的方法以正确编码
I wanted to know how to write a generic method to do so and also a bit curious to see if the generic method improves code maintainability and readability as well我想知道如何编写一个泛型方法来做到这一点,也有点好奇泛型方法是否也提高了代码的可维护性和可读性
You are not be able to convert T in List from T again, the solution that i see is to overload the method like this:您无法再次将 T in List 从 T 转换,我看到的解决方案是重载这样的方法:
public static void Main()
{
WriteReport(new List<List<string>>()
{
new List<string>()
{
"Some Item",
"Onather Item"
},
new List<string>()
{
"Test Item",
"Demo Item"
}
}, "Report Name");
}
private static void WriteReport<T>(List<T> report, string reportName)
{
foreach (var item in report)
{
Console.WriteLine(item);
}
}
private static void WriteReport<T>(List<List<T>> report, string reportName)
{
foreach (var item in report)
{
WriteReport(item, reportName);
}
}
private static void WriteReport<T>(List<List<List<T>>> report, string reportName)
{
foreach (var item in report)
{
WriteReport(item, reportName);
}
}
private static void WriteReport<T>(List<List<List<List<T>>>> report, string reportName)
{
foreach (var item in report)
{
WriteReport(item, reportName);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.