使用 .NET 自定义序列化时测试可选字段
给定这样一个类:
[Serializable]
public class MyClass {
string name;
string address;
public MyClass(SerializationInfo info, StreamingContext context){
name = info.GetString("name");
if(/* todo: check if a value for address exists */)
address = info.GetString("address");
}
public void GetObjectData(SerializationInfo info, StreamingContext context){
info.AddValue(name);
if(address != null)
info.AddValue(address);
}
}
如何在调用 info.GetString(address)
之前测试 address
字段的值是否存在?
是的,我确实知道我可以简单地编写一个空的address
字段,但我真正的问题是早期版本的MyClass
没有地址字段。
注意:我有充分的理由使用自定义序列化。有一些静态字段被用作单例,默认的反序列化将不尊重这一点。
Given a class like this one:
[Serializable]
public class MyClass {
string name;
string address;
public MyClass(SerializationInfo info, StreamingContext context){
name = info.GetString("name");
if(/* todo: check if a value for address exists */)
address = info.GetString("address");
}
public void GetObjectData(SerializationInfo info, StreamingContext context){
info.AddValue(name);
if(address != null)
info.AddValue(address);
}
}
How do I test whether a value for the address
field exists before calling info.GetString(address)
?
Yes, I do understand that I could simply write a null address
field but my real problem is that earlier versions of MyClass
, did not have an address field.
Note: I have good reasons for using custom serialization. There are some static fields that are being used as singletons and the default deserialization will not respect that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,一种有趣的方法是您可以使用 < code>GetEnumerator (
foreach
) 迭代名称/值对,使用名称上的switch
依次处理每个名称/值对?不过,实现似乎有点不标准;从示例这里:
但它看起来像您还可以使用
SerializationEntry
:Well, one intriguing approach is that you could use
GetEnumerator
(foreach
) to iterate over the name/value pairs, using aswitch
on the name to handle each in turn?The implementation seems a bit non-standard, though; from the example here:
But it looks like you can also use
SerializationEntry
:我知道这是一个非常古老的线程,但我对此问题的解决方案是创建 SerializationInfo 类的扩展方法,如下所示:
I know this is a very old thread, but my solution to this issue was to create an extension method of the SerializationInfo class like this:
如果您需要检查多个成员,@Lee Griffin 的答案是低效的,因为它将迭代每个属性的所有成员。
我发现创建一个扩展方法可以更有效地从成员创建字典。如果您只需要测试是否存在,则可以创建一个哈希集以利用比基本列表更快的查找速度。
然后可以简单地使用它:
或
@Lee Griffin answer is inefficient if you need to check multiple members as it will iterate all members for each property.
I found creating a extension method that will create a dictionary from the members more efficient. If you just need to test for existence, you can create a hashset to take advantage of faster lookups then a basic list.
it can then be used simply:
or