Hey..
I just wanted to bring you some information on how to save whole methods/delegates in a well way..
So let's get an example. You're just trying to create a command type and you need to handle an action within this
type to make it executable/invokable, like...
Code:
class Command {
public string Name { get; private set; }
public Action Action { get; private set; }
public Command(string name, Action action) {
this.Name = name;
this.Action = action;
}
public void Execute() {
if (this.Action != null)
this.Action.Invoke();
}
}
This will be the simplest possible structure for it. So you could use it like...
So the main question is: How to f*kin save this type as something you could load again.
Well. Here's the solution...
The first step will be to add the [Serializable] attribute to your command type...
Code:
[Serializable]
class Command {
// you know what goes in here...
}
Now you've made your type serializable as the attribute itself already told you. The second step is to make it easily
savable. Let's add some more functionallity to our type and the using directives System. IO and System.Runtime.Serialization.Formatters.Binary...
Code:
[Serializable]
class Command {
// paste the already known code...
public void Save(string fileName) {
using (var sStream = File.Create(fileName)) {
BinaryFormatter sFormatter = new BinaryFormatter();
sFormatter.Serialize(sStream, this);
sStream.Close();
}
}
public static Command Load(string fileName) {
object result;
using (var dsStream = File.OpenRead(fileName)) {
BinaryFormatter dsFormatter = new BinaryFormatter();
result = dsFormatter.Deserialze(sStream);
dsStream.Close();
}
return (Command)result;
}
}
This methods make it possible to easily save & load your type reference as shown below...
Code:
// except from '.bin' you could use any extension you want or create your own one such as '.command'...
someCommand.Save(@"C:\somefolder\somesubfolder\somefile.bin");
That's it for this tutorial. I hope there's some helpful content in it.If you want to get more information just visit the msdn reference
side and search for the serialization keyword...