简体   繁体   中英

C# “Enum” Serialization - Deserialization to Static Instance

Suppose you have the following class:

class Test : ISerializable {

  public static Test Instance1 = new Test {
    Value1 = "Hello"
    ,Value2 = 86
  };
  public static Test Instance2 = new Test {
    Value1 = "World"
    ,Value2 = 26
  };

  public String Value1 { get; private set; }
  public int Value2 { get; private set; }

  public void GetObjectData(SerializationInfo info, StreamingContext context) {
    //Serialize an indicator of which instance we are - Currently 
    //I am using the FieldInfo for the static reference.
  }
}

I was wondering if it is possible / elegant to deserialize to the static instances of the class?

Since the deserialization routines (I'm using BinaryFormatter, though I'd imagine others would be similar) look for a constructor with the same argument list as GetObjectData() , it seems like this can't be done directly . . Which I would presume means that the most elegant solution would be to actually use an enum , and then provide some sort of translation mechanism for turning an enum value into an instance reference. However, I personally like that the "Enum"'s choices are directly linked with their data.

How might one go about this?

If you need more data with with the Enums, consider using attributes. Example below.

class Name : Attribute
{
    public string Text;

    public Name(string text)
    {
        this.Text = text;
    }
}


class Description : Attribute
{
    public string Text;

    public Description(string text)
    {
        this.Text = text;
    }
}
public enum DaysOfWeek
{
    [Name("FirstDayOfWeek")]
    [Description("This is the first day of 7 days")]
    Sunday = 1,

    [Name("SecondDayOfWeek")]
    [Description("This is the second day of 7 days")]
    Monday= 2,

    [Name("FirstDayOfWeek")]
    [Description("This is the Third day of 7 days")]
    Tuesday= 3,
}

Perhaps this will allow you to provide more information with the Enums. You can access the attributes through reflection. If you need an example to retrieve the attribute I can provide that as well but I'm trying to keep this somewhat short.

Use Enum.Parse ...Suppose you have the following:

Enum myEnum{
   Foo = 1,
   Bar = 2,
   Baz = 3
};

Then

myEnum myE = myEnum.Foo; /* Default! */
   myE = (myEnum)Enum.Parse(myE.GetType(), "Baz"); 
   /* Now, myE should be Baz! */
   Console.WriteLine("Enum Selected: {0}", myE.ToString());

The above sample serves to illustrate how to convert a string literal into an enum. I hope this is what you are looking for.

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