使用 .NET 自定义序列化时测试可选字段

发布于 2024-08-02 21:13:58 字数 777 浏览 4 评论 0原文

给定这样一个类:

[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

瑾夏年华 2024-08-09 21:13:58

好吧,一种有趣的方法是您可以使用 < code>GetEnumerator (foreach) 迭代名称/值对,使用名称上的 switch 依次处理每个名称/值对?

不过,实现似乎有点不标准;从示例这里

    SerializationInfoEnumerator e = info.GetEnumerator();
    Console.WriteLine("Values in the SerializationInfo:");
    while (e.MoveNext())
    {
        Console.WriteLine("Name={0}, ObjectType={1}, Value={2}",
             e.Name, e.ObjectType, e.Value);
    }

但它看起来像您还可以使用SerializationEntry

[Serializable]
class MyData : ISerializable
{
    public string Name { get; set; }
    public int Value { get; set; }

    public MyData() { }
    public MyData(SerializationInfo info, StreamingContext context)
    {
        foreach (SerializationEntry entry in info)
        {
            switch (entry.Name)
            {
                case "Name":
                    Name = (string)entry.Value; break;
                case "Value":
                    Value = (int)entry.Value; break;
            }
        }
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Name", Name);
        info.AddValue("Value", Value);
    }
}

Well, one intriguing approach is that you could use GetEnumerator (foreach) to iterate over the name/value pairs, using a switch on the name to handle each in turn?

The implementation seems a bit non-standard, though; from the example here:

    SerializationInfoEnumerator e = info.GetEnumerator();
    Console.WriteLine("Values in the SerializationInfo:");
    while (e.MoveNext())
    {
        Console.WriteLine("Name={0}, ObjectType={1}, Value={2}",
             e.Name, e.ObjectType, e.Value);
    }

But it looks like you can also use SerializationEntry:

[Serializable]
class MyData : ISerializable
{
    public string Name { get; set; }
    public int Value { get; set; }

    public MyData() { }
    public MyData(SerializationInfo info, StreamingContext context)
    {
        foreach (SerializationEntry entry in info)
        {
            switch (entry.Name)
            {
                case "Name":
                    Name = (string)entry.Value; break;
                case "Value":
                    Value = (int)entry.Value; break;
            }
        }
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Name", Name);
        info.AddValue("Value", Value);
    }
}
醉城メ夜风 2024-08-09 21:13:58

我知道这是一个非常古老的线程,但我对此问题的解决方案是创建 SerializationInfo 类的扩展方法,如下所示:

namespace System.Runtime.Serialization
{
  public static class SerializationInfoExtensions
  {
    public static bool Exists(this SerializationInfo info, string name)
    {
      foreach (SerializationEntry entry in info)
        if (name == entry.Name)
          return true;
      return false;
    }
  }
}

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:

namespace System.Runtime.Serialization
{
  public static class SerializationInfoExtensions
  {
    public static bool Exists(this SerializationInfo info, string name)
    {
      foreach (SerializationEntry entry in info)
        if (name == entry.Name)
          return true;
      return false;
    }
  }
}
若相惜即相离 2024-08-09 21:13:58

如果您需要检查多个成员,@Lee Griffin 的答案是低效的,因为它将迭代每个属性的所有成员。

我发现创建一个扩展方法可以更有效地从成员创建字典。如果您只需要测试是否存在,则可以创建一个哈希集以利用比基本列表更快的查找速度。

// if you don't care about the object type then you can replace the tuple with just object
public static Dictionary<string, Tuple<Type, object>> GetSerializedMemberDictionary(this SerializationInfo information)
{
    var memberDict = new Dictionary<string, Tuple<Type, object>>(information.MemberCount);
    foreach (SerializationEntry entry in information)
       memberDict.Add(entry.Name, Tuple.Create(entry.ObjectType, entry.Value));
    return memberDict;
}

public static HashSet<string> GetSerializedMemberList(this SerializationInfo information)
{
    var list = new HashSet<string>(information.MemberCount);
    foreach (SerializationEntry entry in information)
       list.Add(entry.Name);
    return list;
}

然后可以简单地使用它:

var members = information.GetSerializedMemberDictionary();
if (members.ContainsKey("Delimiter")) {
   _delimiter = (string)members["Delimiter"].Item2;
}
        

var members = information.GetSerializedMemberList();
var delimiter = members.Contains("Delimiter") ? information.GetString("Delimiter") : null;

        

@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.

// if you don't care about the object type then you can replace the tuple with just object
public static Dictionary<string, Tuple<Type, object>> GetSerializedMemberDictionary(this SerializationInfo information)
{
    var memberDict = new Dictionary<string, Tuple<Type, object>>(information.MemberCount);
    foreach (SerializationEntry entry in information)
       memberDict.Add(entry.Name, Tuple.Create(entry.ObjectType, entry.Value));
    return memberDict;
}

public static HashSet<string> GetSerializedMemberList(this SerializationInfo information)
{
    var list = new HashSet<string>(information.MemberCount);
    foreach (SerializationEntry entry in information)
       list.Add(entry.Name);
    return list;
}

it can then be used simply:

var members = information.GetSerializedMemberDictionary();
if (members.ContainsKey("Delimiter")) {
   _delimiter = (string)members["Delimiter"].Item2;
}
        

or

var members = information.GetSerializedMemberList();
var delimiter = members.Contains("Delimiter") ? information.GetString("Delimiter") : null;

        
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文