【问题标题】:Exception while deserializing DataTable with custom DataType columns using BinaryFormatter使用 BinaryFormatter 反序列化具有自定义 DataType 列的 DataTable 时出现异常
【发布时间】:2015-04-28 12:56:43
【问题描述】:

我正在编写一个客户端-服务器应用程序。我想发送DataTable table,其中大多数列都是 Pair 类型。我在服务器和客户端的public class Struct 中都有public class Pair

[Serializable]
public class Struct
{
    public class Pair
    {
        public int a { get; set; }
        public int b { get; set; }
            ...
        public override string ToString()
        {
            return this.a.ToString() + " " + this.b.ToString();
        }
    }
        ...
}

我从服务器发送它:

(new BinaryFormatter()).Serialize(nStream, table);

在客户端接受:

DataTable table = (DataTable)(new BinaryFormatter()).Deserialize(nStream);

在这里我得到一个

TargetInvocationException "异常已被调用的目标抛出" with InnerException: ArgumentException“列需要有效的数据类型”。

如何通过网络发送该表并反序列化?

【问题讨论】:

    标签: c# serialization datatable binaryformatter


    【解决方案1】:

    您还需要将内部类标记为[Serializable]

    [Serializable]
    public class Struct
    {
        [Serializable]
        public class Pair
        {
            public int a { get; set; }
            public int b { get; set; }
        }
    }
    

    嵌套类不是子类,它是一个 independent type,碰巧可以访问其包含类型的受保护和私有成员。

    另外,您实际上是在客户端和服务器中链接包含您的Struct相同的assembly,还是只是复制代码? BinaryFormatter 实际上记录了被序列化类型的程序集名称和版本,如果在反序列化时找不到该特定程序集,则反序列化将失败。见How to serialize/deserialize an object loaded from another assembly?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 2015-12-09
      相关资源
      最近更新 更多