【问题标题】:List<> to MemoryStream ConversionList<> 到 MemoryStream 的转换
【发布时间】:2020-02-19 05:45:53
【问题描述】:

您好,我是 C# 新手,我想将 List 类型转换为 MemoryStream:

List<String> listType=new List<String>;
MemoryStream ms=new MemoryStream();

如果我这样做-

MemoryStream listToStream=(MemoryStream)listType;

显示为可疑演员表。 请帮忙!!

【问题讨论】:

  • 您无法将列表转换为内存流。这是两种完全不同的类型。你可能想序列化它吗?如果是这样,您是否关心它的序列化方式(JSON、XML、二进制)?
  • 所以一个列表是......好吧,一个东西的列表,在这种情况下是字符串,MemoryStream 是一个byte 的数组。你想如何魔法他们。你需要发明一些规则,只有知道这些规则,我们才能帮助你
  • @nvoigt 是的,我想序列化它..有什么办法吗?

标签: c# stream


【解决方案1】:

如果序列化是你想要的,那么是xml还是json?

它们在性能方面几乎相同:Json and Xml serialization, what is better performance?

一个很好的例子如下:http://www.daveoncsharp.com/2009/07/xml-serialization-of-collections/

using System;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace XMLSerialization
{  
    [XmlRoot("CompanyEmployees")]
    public class EmployeeList
    {
        [XmlArray("EmployeeListing")]

        [XmlArrayItem("Employee", typeof(Employee))]
        public List employeeList;

        // Constructor
        public EmployeeList()
        {
            employeeList = new List();
        }

        public void AddEmployee(Employee employee)
        {
            employeeList.Add(employee);
        }
    }
}

以及实际的序列化

private void SerializeList()
{
    // Create an instance of the EmployeeList class
    EmployeeList employeeList = new EmployeeList();

    // Create a few instances of the Employee class
    Employee emp1 = new Employee();
    emp1.Name = "John";
    emp1.Surname = "Smith";
    emp1.DateOfBirth = new DateTime(1980, 10, 08);
    emp1.Sex = Employee.EmployeeSex.Male;
    emp1.Position = "Software Engineer";

    Employee emp2 = new Employee();
    emp2.Name = "David";
    emp2.Surname = "McGregor";
    emp2.DateOfBirth = new DateTime(1973, 01, 13);
    emp2.Sex = Employee.EmployeeSex.Male;
    emp2.Position = "Product Manager";

    Employee emp3 = new Employee();
    emp3.Name = "Sarah";
    emp3.Surname = "Crow";
    emp3.DateOfBirth = new DateTime(1983, 11, 23);
    emp3.Sex = Employee.EmployeeSex.Female;
    emp3.Position = "Software Tester";

    // Add the employees to the list   
    employeeList.AddEmployee(emp1);
    employeeList.AddEmployee(emp2);
    employeeList.AddEmployee(emp3);

    // Create an instance of System.Xml.Serialization.XmlSerializer
    XmlSerializer serializer = new XmlSerializer(employeeList.GetType());

    // Create an instance of System.IO.TextWriter 
    // to save the serialized object to disk
    TextWriter textWriter = new StreamWriter("C:\\Employee\\employeeList.xml");

    // Serialize the employeeList object
    serializer.Serialize(textWriter, employeeList);

    // Close the TextWriter
    textWriter.Close();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多