【发布时间】:2016-07-11 08:29:31
【问题描述】:
我正在尝试创建保存到文件的报价列表。一旦引号显示在控制台上,我会将布尔值更改为 true。该索引用于处理要在控制台上显示的报价。首先我尝试了 File.WriteAllLines,但这不适用于我的 Quotes-class。
似乎我尝试将列表序列化为文件可以正常工作,但我无法弄清楚如何在应该从文件读取到 myList2 的代码中删除 CS1061。
我真的很想得到一些反馈。代码仅供自己学习和娱乐。
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Quotes
{
// A quote followed by a bool to show if it has been showed recently and an index to navigate the list.
[Serializable]
class Quotes
{
private string quote;
private bool shown;
private int index;
public Quotes(string _quote, bool _shown, int _index)
{
quote = _quote;
shown = _shown;
index = _index;
}
public string Quote
{
get
{
return quote;
}
set
{
quote = value;
}
}
public bool Shown
{
get
{
return shown;
}
set
{
shown = value;
}
}
public int Index
{
get
{
return index;
}
set
{
index = value;
}
}
public override string ToString()
{
return string.Format("{0} {1} {2}", quote, shown, index);
}
}
class Program
{
static void Main(string[] args)
{
// Set a variable to the My Documents path.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//List<Quotes> myList = new List<Quotes>();
var myList = new List<Quotes>();
myList.Add(new Quotes("One", false, 1));
myList.Add(new Quotes("Two", false, 2));
myList.Add(new Quotes("Three", false, 3));
myList.Add(new Quotes("Four", false, 4));
//Write the list to a file. Expand to accept user input and add at the end of the file.
try
{
using (Stream stream = File.Open(mydocpath + @"\WriteLines.txt", FileMode.Create))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, myList);
}
}
catch (IOException)
{
}
//Read from a file and write to the list.Put in a method when it works.
try
{
using (Stream stream = File.Open(mydocpath + @"\WriteLines.txt", FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
var myList2 = (List<Quotes>)bin.Deserialize(stream);
foreach (var quote in myList2)
{
//Why is this not working? Where should I define quote??
Console.WriteLine("{0}, {1}, {2}", myList2.quote, myList2.shown, myList2.index);
}
}
}
catch (IOException)
{
}
}
}
}
【问题讨论】:
-
要查看您的代码,这是第二个问题的正确位置:codereview.stackexchange.com
-
第一条反馈:格式化你的代码。第二条反馈:了解自动实现的属性。第三条反馈:提供minimal reproducible example,它会比这更短,并且更准确地说明错误。
-
@PriyankKapadia:听起来这不是真的代码审查(这也是我的第一个想法),因为 OP 正试图摆脱错误,但不能想办法做到这一点。
-
@PriyankKapadia:当然不完全清楚——但我想说的是,虽然代码不起作用,但它是这里的主题,而不是代码审查。
标签: c# list serialization deserialization