After having my class go through binary serialization any references to static instance of another class break. The example should explain better what i mean:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace staticorsingletontest
{
[System.Serializable]
public class weapon
{
public string name;
public weapon (string name)
{ this.name = name; }
}
class Program
{
public static weapon sword = new weapon("Sword");
public static weapon axe = new weapon("Axe");
static void Main(string[] args)
{
byte[] b;
Dictionary<weapon, int> WarriorSkills = new Dictionary<weapon,int>();
Dictionary<weapon, int> Des = new Dictionary<weapon,int>();
WarriorSkills.Add(sword, 10);
using (MemoryStream ms = new MemoryStream())
{
//Serialize
new BinaryFormatter().Serialize(ms, WarriorSkills);
b = ms.ToArray();
//Deserialize
ms.Flush();
ms.Write(b, 0, b.Length);
ms.Seek(0, SeekOrigin.Begin);
Des = (Dictionary<weapon, int>)new BinaryFormatter().Deserialize(ms);
}
Console.WriteLine(WarriorSkills.Keys.ToArray()[0].name + " is a " + Des.Keys.ToArray()[0].name + ", but are they equal? " + (WarriorSkills.Keys.ToArray()[0] == Des.Keys.ToArray()[0]).ToString());
Console.ReadLine();
Console.WriteLine("Warrior's Skill with Sword is ", Des[sword]); //wonderful "KeyNotFoundException" error
Console.ReadLine();
}
}
}
Program throws an error because deserialized "sword" is not the same "sword" (its static
, how that even happens?)
Making weapon
class a singleton
would not work because then sword and axe will be the same thing.
Is there a way to point out that both swords are the same thing, or i dont get some core logic of static
classes?