C#“枚举”序列化-反序列化为静态实例
假设您有以下类:
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.
}
}
我想知道是否可以/优雅地反序列化为该类的静态实例?
由于反序列化例程(我正在使用 BinaryFormatter,尽管我想象其他例程会类似)会查找具有与 GetObjectData()
相同参数列表的构造函数,因此这似乎不可能直接完成。 。我认为这意味着最优雅的解决方案是实际使用枚举,然后提供某种转换机制将枚举值转换为实例引用。然而,我个人喜欢“Enum”的选择与其数据直接相关。
人们可以怎样做呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要更多带有枚举的数据,请考虑使用属性。下面的例子。
也许这将使您能够通过枚举提供更多信息。您可以通过反射访问属性。如果您需要一个示例来检索属性,我也可以提供,但我试图保持简短。
If you need more data with with the Enums, consider using attributes. Example below.
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.
使用 Enum.Parse ...假设您有以下:
然后
上面的示例用于说明如何将字符串文字转换为枚举。我希望这就是您正在寻找的。
Use Enum.Parse...Suppose you have the following:
Then
The above sample serves to illustrate how to convert a string literal into an enum. I hope this is what you are looking for.