C#"枚举"序列化 - 反序列化为静态实例

Wal*_*t W 4 c# enums serialization static

假设您有以下课程:

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.
  }
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否可能/优雅地反序列化到类的静态实例?

由于反序列化例程(我正在使用BinaryFormatter,虽然我想其他人会类似)寻找具有相同参数列表的构造函数GetObjectData(),但似乎这不能直接完成..我认为这意味着最优雅的解决方案是实际使用a enum,然后提供某种转换机制来将枚举值转换为实例引用.但是,我个人认为"Enum"的选择与他们的数据直接相关.

怎么会这样呢?

gal*_*13x 5

如果您需要使用Enums的更多数据,请考虑使用属性.以下示例.

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,
}
Run Code Online (Sandbox Code Playgroud)

也许这将允许您使用Enums提供更多信息.您可以通过反射访问属性.如果你需要一个例子来检索我可以提供的属性,但我试图保持这个有点短.