I trying to write universal function, that can fill List<OfAnyObjects> from file, line by line.
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.");
}
}
It gives an error (translated from Russian):
Argument "2": type conversion from "System.Collections.Generic.List<string>" to "System.Collections.Generic.List<object>" impossible(CS1503) - C:\...\Program.cs:N,N
Trying to do one of that:
fileToList("./test.txt", strList as List<object>, strProc);
OR
fileToList("./test.txt", (List<object>)strList, strProc);
Does't seems to help.
Have you any ideas how to do that?
And, sorry for my English, it's not my native language.
Thank you for your help.
The correct (working) solution:
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);
//...
}
}