簡體   English   中英

如何將鏈接列表保存到文本文件? 在C#中

[英]how to save the linked list to text file? in C#

如何將這些內容保存在文本文件中? 在C#中

using System;
using System.Collections.Generic;
using System.Text;

namespace LinkList
{
    class Program
    {
        static void Main(string[] args)
        {

            list x = null;
            list first;
            Random rnd = new Random();
            x = new list();
            first = x;
            x.data = rnd.Next(20, 500);
            x.next = null;
            for (int i = 0; i < 20; i++)
            {
                x.next = new list(); //create new node
                x = x.next;
                x.next = null;
                //x.data = System.Convert.ToInt32(Console.ReadLine());
                x.data = rnd.Next(20, 500);
            }
            x = first;
            int count = 0;
            int y;
            while (x != null)
            {
                Console.WriteLine(x.data);
                x = x.next;

            }
        }
    }
    class list
    {
        public int data; //4 byte
        public list next;  // 4 byte
    }
}

一種可能的方法是序列化它。 JSON是一種非常標准的格式,因此您可以使用JSON序列化程序,例如Newtonsoft.JSON

string json = JsonConvert.SerializeObject(first);
File.WriteAllText("list.txt", json);

或者,如果您不想使用第三方庫,則可以使用框架中內置的JavaScriptSerializer類來實現相同目的:

string json = new JavaScriptSerializer().Serialize(first);
File.WriteAllText("list.txt", json);

如果您更喜歡XML作為序列化格式,則可以這樣做:

var serializer = new XmlSerializer(typeof(list));
using (var output = File.OpenWrite("list.xml"))
{
    serializer.Serialize(output, first);
}

為此,您可能需要使listpublic因為在您的示例中它是internal

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM