Rob*_*bin 2 .net c# object winforms
我有一个WriteList
将列表保存到文件中的函数.此函数具有参数,List<Object>
因此我可以将不同类型的列表作为参数传递.
public void WriteList(List<object> input, string ListName)
{
WriteToFile("List - " + ListName);
foreach (object temp in input)
{
WriteToFile(temp.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
从我的代码调用此函数时,我想传递参数List<Database>
where Database
我自己的类.我收到以下错误:
无法从'System.Collections.Generic.List -Database-'转换为'System.Collections.Generic.List-object-'
所以我的问题是如何将我自己的类转换为Object,然后将列表传递给我的函数.
Mar*_*zek 14
List<T>
是不协变的.IEnumerable<T>
改为使用:
public void WriteList(IEnumerable<object> input, string ListName)
{
WriteToFile("List - " + ListName);
foreach (object temp in input)
{
WriteToFile(temp.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
或者使方法通用:
public void WriteList<T>(List<T> input, string ListName)
{
WriteToFile("List - " + ListName);
foreach (T temp in input)
{
WriteToFile(temp.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
IMO:第二个更好,因为与值类型一起使用时没有装箱/拆箱.
归档时间: |
|
查看次数: |
229 次 |
最近记录: |