Here is a method used to save data to a file which has stumped me:
public void SaveData(string filename, Action<StreamWriter> saveAction)
The documentation for the library describes the second parameter as "A delegate action to handle actually writing the data". I am lost, however, on how to actually create an action for a StreamWriter. I've done some research and found a lot of stuff like this used as examples for Action<T>
:
Action<string> s = Console.WriteLine;
And from that I infer that <T>
is the parameter type passed and the Action
is the method which takes this parameter. I am aware that this may be terribly wrong.
Basically all I want to do is use StreamWriter.WriteLine(string line)
. However, I cannot use
Action<StreamWriter> s = StreamWriter.WriteLine;
Because that makes no sense, plus it is impossible for me to reference StreamWriter.WriteLine
anyway. Right now I'm thinking that there must be a method which takes StreamWriter
from a class which I am not aware of. If anyone would care to point me in the right direction I would be very grateful.
You may ask why I can't just create my own StreamWriter
and do it the way I've always done it. Well, I'm working in XNA on the Zune, so writing to a text file is actually quite d开发者_如何学编程ifficult with all the levels of protection (all apps are sandboxed), and the libraries I'm using right now promise to make it far more streamlined if I can just figure out how to use Action<T>
effectively. Plus, I want to learn and be better equipped to use delegates in the future.
Probably the API is intended to be used like this:
SaveData(filename, writer => writer.WriteLine(saveData));
The => notation concisely declares an anonymous function. You could write it in a longer fashion like this:
private static void SaveToWriter(StreamWriter writer)
{
// get saveData somehow
writer.WriteLine(saveData);
}
// ...
SaveData(filename, SaveToWriter);
which might help explicate the type signatures involved.
精彩评论