vendredi 16 décembre 2016

C# - Serializing and deserializing methods

Firstly, sorry if this has been answered elsewhere; I looked around, but the few threads and pages I found on this topic confused me quite a bit as I am fairly new to serialisation. I am making a C# application in which I want to be able to send a function over the Internet. After a quick Google search, I came across serialization. I attempted to serialize and deserialize my method with the following:

public static string ObjectToString(object obj)
{
    using (MemoryStream ms = new MemoryStream())
    {
        new BinaryFormatter().Serialize(ms, obj);
        return Convert.ToBase64String(ms.ToArray());
    }
}

public static object StringToObject(string base64String)
{
    byte[] bytes = Convert.FromBase64String(base64String);
    using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
    {
        ms.Write(bytes, 0, bytes.Length);
        ms.Position = 0;
        return new BinaryFormatter().Deserialize(ms);
    }
}

But it threw an exception when attempting to convert to a string. I added [Serializable()] to it, and then the method simply did nothing.

After some more Googling, I found that in C# you can't do this with the default methods. So is it possible to do this at all, and if not, is there any practical way to go about sending a method over a TcpClient? Sorry if this is a stupid question.

Thanks in advance,

-Matthew




Aucun commentaire:

Enregistrer un commentaire