简体   繁体   中英

C# - Serializing and deserializing static member

I have a static dictionary in my class which holds 12000 values. When I try to save my class I need to refresh and add some data in static dictionary at server side.

The problem is that after adding the values into static dicitionary, it still retains 12000 values, not 12001 (the last one doesn't get added). It's not able to serialize and deserialize the static member.

I think, as static member are not part of the object, so it doesn't get seralized. I can implement ISerializable interface and add the last member. But I think it's not a good idea.

Is there a better way to do that? I'm working on C# Windows application.

You may serialize. Here is a code,

[Serializable ]
public class Numbers
{
    public int no;
    public static int no1;
}
class Test
{
    static void Deser()
    {
        Numbers a;
        FileStream fs = new FileStream("a1.txt", FileMode.Open );
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bs = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        a = (Numbers)bs.Deserialize(fs);
        Numbers.no1 = (int)bs.Deserialize(fs);
        fs.Close();
        Console.WriteLine(a.no + " " + Numbers.no1);
    }
    static void Ser()
    {
        Numbers a = new Numbers();
        a.no = 100;
        Numbers.no1 = 200;

        FileStream fs = new FileStream("a1.txt", FileMode.Create);
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bs = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        bs.Serialize(fs, a);
        bs.Serialize(fs, Numbers.no1);
        fs.Close();
   }
}

What behaviour would you expect if you sent data from several different clients to the server?

Suppose client A had added items X and Y, and client B had added items Y and Z. I'm guessing that you'd want the static dictionazry to end up with item X, Y and Z, but not two Ys.

I think you will need to special code in your ISerializable implementation, and I think that's quite legitimate.

I would have an extra non-static member list variable called something like "myDictionaryAdditions" when ever I add to static dictionary I would add to this list. Presumably this will get correctly trasnfered to the server. Now you just need some code in teh de-serializer to transfer non-dups to the static dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM