将 Stream 反序列化为 List 或任何其他类型

2024-05-09

尝试将流反序列化为List<T>(或任何其他类型)并且失败并出现错误:

方法的类型参数Foo.Deserialize<T>(System.IO.Stream)无法从用法推断。尝试显式指定类型参数。

这失败了:

public static T Deserialize<T>(this Stream stream)
{
    BinaryFormatter bin = new BinaryFormatter();
    return (T)bin.Deserialize(stream);
}

但这有效:

public static List<MyClass.MyStruct> Deserialize(this Stream stream)
{
    BinaryFormatter bin = new BinaryFormatter();
    return (List<MyClass.MyStruct>)bin.Deserialize(stream);
}

or:

public static object Deserialize(this Stream stream)
{
    BinaryFormatter bin = new BinaryFormatter();
    return bin.Deserialize(stream);
}

是否可以在不进行铸造的情况下做到这一点,例如(List<MyStruct>)stream.Deserialize()?

Update:
Using stream.Deserialize<List<MyClass.MyStruct>>()结果出现错误:

System.InvalidCastException: Unable to cast object of type 'System.RuntimeType'
to type 'System.Collections.Generic.List`1[MyClass+MyStruct]'.
at StreamExtensions.Deserialize[T](Stream stream)
at MyClass.RunSnippet()

更新 2(示例控制台应用程序)- 运行一次创建文件,再次运行以读取文件

using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;

public static class StreamExtensions
{
    public static Stream Serialize<T>(this T o) where T : new()
    {
        Stream stream = new MemoryStream();
        BinaryFormatter bin = new BinaryFormatter();
        bin.Serialize(stream, typeof(T));
        return stream;
    }

    public static T Deserialize<T>(this Stream stream) where T : new()
    {
        BinaryFormatter bin = new BinaryFormatter();
        return (T)bin.Deserialize(stream);
    }

    public static void WriteTo(this Stream source, Stream destination)
    {
        byte[] buffer = new byte[32768];
        source.Position = 0;
        if(source.Length < buffer.Length) buffer = new byte[source.Length];
        int read = 0;
        while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
        {
            destination.Write(buffer, 0, read);
        }
    }
}


public class MyClass
{
    public struct MyStruct
    {
        public string StringData;
        public MyStruct(string stringData)
        {
            this.StringData = stringData;
        }
    }

    public static void Main()
    {
        // binary serialization
        string filename_bin = "mydata.bin";
        List<MyStruct> l;
        if(!File.Exists(filename_bin))
        {
            Console.WriteLine("Serializing to disk");
            l = new List<MyStruct>();
            l.Add(new MyStruct("Hello"));
            l.Add(new MyStruct("Goodbye"));
            using (Stream stream = File.Open(filename_bin, FileMode.Create))
            {
                Stream s = l.Serialize();
                s.WriteTo(stream);
            }
        }
        else
        {
            Console.WriteLine("Deserializing from disk");
            try
            {
                using (Stream stream = File.Open(filename_bin, FileMode.Open))
                {
                    l = stream.Deserialize<List<MyStruct>>();
                }
            }
            catch(Exception ex)
            {
                l = new List<MyStruct>();
                Console.WriteLine(ex.ToString());
            }
        }

        foreach(MyStruct s in l)
        {
            Console.WriteLine(
                string.Format("StringData: {0}",
                    s.StringData
                )
            );
        }

        Console.ReadLine();
    }
}

我假设您像这样调用扩展方法:

List<MyStruct> result = mystream.Deserialize();    

在这种情况下,编译器无法确定T for Deserialize(它不查看方法调用结果分配给的变量)。

因此,您需要显式指定类型参数:

List<MyStruct> result = mystream.Deserialize<List<MyStruct>>();

这有效:

public static class StreamExtensions
{
    public static void SerializeTo<T>(this T o, Stream stream)
    {
        new BinaryFormatter().Serialize(stream, o);  // serialize o not typeof(T)
    }

    public static T Deserialize<T>(this Stream stream)
    {
        return (T)new BinaryFormatter().Deserialize(stream);
    }
}

[Serializable]  // mark type as serializable
public struct MyStruct
{
    public string StringData;
    public MyStruct(string stringData)
    {
        this.StringData = stringData;
    }
}

public static void Main()
{
    MemoryStream stream = new MemoryStream();

    new List<MyStruct> { new MyStruct("Hello") }.SerializeTo(stream);

    stream.Position = 0;

    var mylist = stream.Deserialize<List<MyStruct>>();  // specify type argument
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 Stream 反序列化为 List 或任何其他类型 的相关文章

  • 如何使用 C# 中的参数将用户重定向到 paypal

    如果我有像下面这样的简单表格 我可以用它来将用户重定向到 PayPal 以完成付款
  • GLKit的GLKMatrix“列专业”如何?

    前提A 当谈论线性存储器中的 列主 矩阵时 列被一个接一个地指定 使得存储器中的前 4 个条目对应于矩阵中的第一列 另一方面 行主 矩阵被理解为依次指定行 以便内存中的前 4 个条目指定矩阵的第一行 A GLKMatrix4看起来像这样 u
  • 为什么两个不同的 Base64 字符串的转换会返回相等的字节数组?

    我想知道为什么从 base64 字符串转换会为不同的字符串返回相同的字节数组 const string s1 dg const string s2 dq byte a1 Convert FromBase64String s1 byte a2
  • 不支持将数据直接绑定到存储查询(DbSet、DbQuery、DbSqlQuery)

    正在编码视觉工作室2012并使用实体模型作为我的数据层 但是 当页面尝试加载时 上面提到的标题 我使用 Linq 语句的下拉控件往往会引发未处理的异常 下面是我的代码 using AdventureWorksEntities dw new
  • ASP.NET MVC:这个业务逻辑应该放在哪里?

    我正在开发我的第一个真正的 MVC 应用程序 并尝试遵循一般的 OOP 最佳实践 我正在将控制器中的一些简单业务逻辑重构到我的域模型中 我最近一直在阅读一些内容 很明显我应该将逻辑放在域模型实体类中的某个位置 以避免出现 贫血域模型 反模式
  • 类模板参数推导 - clang 和 gcc 不同

    下面的代码使用 gcc 编译 但不使用 clang 编译 https godbolt org z ttqGuL template
  • 不同枚举类型的范围和可转换性

    在什么条件下可以从一种枚举类型转换为另一种枚举类型 让我们考虑以下代码 include
  • WCF 中 SOAP 消息的数字签名

    我在 4 0 中有一个 WCF 服务 我需要向 SOAP 响应添加数字签名 我不太确定实际上应该如何完成 我相信响应应该类似于下面的链接中显示的内容 https spaces internet2 edu display ISWG Signe
  • SolrNet连接说明

    为什么 SolrNet 连接的容器保持静态 这是一个非常大的错误 因为当我们在应用程序中向应用程序发送异步请求时 SolrNet 会表现异常 在 SolrNet 中如何避免这个问题 class P static void M string
  • 转发声明和包含

    在使用库时 无论是我自己的还是外部的 都有很多带有前向声明的类 根据情况 相同的类也包含在内 当我使用某个类时 我需要知道该类使用的某些对象是前向声明的还是 include d 原因是我想知道是否应该包含两个标题还是只包含一个标题 现在我知
  • 如何在 C 中调用采用匿名结构的函数?

    如何在 C 中调用采用匿名结构的函数 比如这个函数 void func struct int x p printf i n p x 当提供原型的函数声明在范围内时 调用该函数的参数必须具有与原型中声明的类型兼容的类型 其中 兼容 具有标准定
  • 垃圾收集器是否在单独的进程中运行?

    垃圾收集器是否在单独的进程中启动 例如 如果我们尝试测量某段代码所花费的进程时间 并且在此期间垃圾收集器开始收集 它会在新进程上启动还是在同一进程中启动 它的工作原理如下吗 Code Process 1 gt Garbage Collect
  • 如何查看网络连接状态是否发生变化?

    我正在编写一个应用程序 用于检查计算机是否连接到某个特定网络 并为我们的用户带来一些魔力 该应用程序将在后台运行并执行检查是否用户请求 托盘中的菜单 我还希望应用程序能够自动检查用户是否从有线更改为无线 或者断开连接并连接到新网络 并执行魔
  • 为什么编译时浮点计算可能不会得到与运行时计算相同的结果?

    In the speaker mentioned Compile time floating point calculations might not have the same results as runtime calculation
  • 通过指向其基址的指针删除 POD 对象是否安全?

    事实上 我正在考虑那些微不足道的可破坏物体 而不仅仅是POD http en wikipedia org wiki Plain old data structure 我不确定 POD 是否可以有基类 当我读到这个解释时is triviall
  • 如何将带有 IP 地址的连接字符串放入 web.config 文件中?

    我们当前在 web config 文件中使用以下连接字符串 add name DBConnectionString connectionString Data Source ourServer Initial Catalog ourDB P
  • C# 模拟VolumeMute按下

    我得到以下代码来模拟音量静音按键 DllImport coredll dll SetLastError true static extern void keybd event byte bVk byte bScan int dwFlags
  • IEnumreable 动态和 lambda

    我想在 a 上使用 lambda 表达式IEnumerable
  • C# - OutOfMemoryException 在 JSON 文件上保存列表

    我正在尝试保存压力图的流数据 基本上我有一个压力矩阵定义为 double pressureMatrix new double e Data GetLength 0 e Data GetLength 1 基本上 我得到了其中之一pressur
  • 使用.NET技术录制屏幕视频[关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 有没有一种方法可以使用 NET 技术来录制屏幕 无论是桌面还是窗口 我的目标是免费的 我喜欢小型 低

随机推荐