我试图编写通用函数,它可以从文件中逐行填充 List<OfAnyObjects> 。
using System.IO;
using System.Collections.Generic;
class Program{
public delegate object stringProcessing(string str);
public static void Main(string[] args){
List<string> strList = new List<string>();
stringProcessing strProc = stringPorc;
fileToList("./test.txt", strList, strProc);
}
public static object stringPorc(string str){
return(str + " " + str);
}
public static void fileToList(string path, List<object> lst, stringProcessing SP){
if(File.Exists(path)){
FileStream fs = new FileStream(path, FileMode.Open);
StreamReader sr = new StreamReader(fs);
string cl;
while((cl = sr.ReadLine()) != null) lst.Add(SP(cl));
sr.Close();
fs.Close();
}
else Service.WLLog("Error: File \"" + path + "\" does't seems to exist.");
}
}
它给出了一个错误(从俄语翻译):
Argument "2": type conversion from "System.Collections.Generic.List<string>" to "System.Collections.Generic.List<object>" impossible(CS1503) - C:\...\Program.cs:N,N
尝试做其中之一:
fileToList("./test.txt", strList as List<object>, strProc);
OR
fileToList("./test.txt", (List<object>)strList, strProc);
似乎没有帮助。
你有什么想法吗?而且,对不起我的英语,它不是我的母语。
谢谢您的帮助。正确的(工作)解决方案:
class Program{
//...
public static void Main(string[] args){
//...
fileToList<string>("./test.txt", strList, strProc);
}
//...
public static void fileToList<T>(string path, List<T> lst, stringProcessing SP) where T : class{
//...
lst.Add(SP(cl) as T);
//...
}
}