c# Generic List
I m populating data for different entities into set of lists using generic lists as follows :
List<Foo> foos ..
List<Bar> bars ..
I need to write these lists to a file, i do have a util method to get the values of properties etc. using reflection.
What i want to do is: using a single method to write these into files such as:
void writeToFile(a generic list)
{
//Which i will write to file here.
}
How can i do this?
开发者_JS百科I want to be able to call :
writeToFile(bars);
writeToFile(foos);
void writeToFile<T>(List<T> list)
{
// Do the writing
}
You can use generics to allow the caller to specify the expected type the list contains.
void writeToFile<T>(IList<T> list)
{
...
}
Probably something like...
private void WriteToFile<T>(
IEnumerable<T> elementsToWrite,
Func<T, string> convertElementToString) {
foreach (var element in elementsToWrite)
{
var stringRepresentation = convertElementToString(element);
// do whatever other list-stuff you need to do
}
}
// called like so...
WriteToFile(listOfFoo, foo => foo.FP1 + ", " + foo.FP2 + " = " foo.FP3);
WriteToFile(listOfBar, bar => bar.BP1 +"/"+ bar.BP2 + "[@x='" + bar.BP3 + "']");
...or you could try something like...
private void WriteToFile<T>(
IEnumerable<T> elementsToWrite,
Action<T, TextWriter> writeElement) {
var writer = ...;
foreach (var element in elementsToWrite)
{
// do whatever you do before you write an element
writeElement(element, writer);
// do whatever you do after you write an element
}
}
// called like so...
WriteToFile(listOfFoo, (foo, writer) =>
writer.Write("{0}, {1} = {2}", foo.FP1, foo.FP2, foo.FP3));
WriteToFile(listOfBar, (bar, writer) =>
writer.Write("{0}/{1}[@x='{2}']", bar.BP1, bar.BP2, bar.BP3));
...or whatever... you get the idea.
You should look into the topic of serialization. There is are some articles out there about dealing with generic types.
精彩评论