【问题标题】:Initializing of objects with data from text files使用文本文件中的数据初始化对象
【发布时间】:2016-10-16 05:10:08
【问题描述】:

我有 2 个班级,一个“自行车”和一个“用户”。第一个有以下属性:

private readonly int codeB;
private string name_parking_station;
int km_made;

第二个:

private string name;
private int codeB;
private int utilization_duration;

两个类都有带参数的构造函数和getter/setter。我的问题是:如何使用我创建的文本文件中的数据实例化两个类中的对象?还有,如何将它们添加到 2 个不同的 ListView-s 中?

【问题讨论】:

  • 很好,文本文件看起来如何?你有什么例子吗?
  • 100 //codeB Grozavesti // name_parking_station 20 // km_made
  • 如果您能够读取文本文件属性,那么您可以使用 REFLECTION 将所有属性注入到类变量中。查看此链接以获取有关 reflection 的指导

标签: c# oop object


【解决方案1】:

如果您的 Bicycle 行不包含那些“//”部分,仅包含您的数据,则可以通过逐行读取文件并按如下方式处理这些行来轻松创建 Bicycle 对象:

// let your class have an appropriate creator
internal Bicycle(int codeB, string name_parking_station, int km_made)
{
    this.codeB = codeB;
    this.name_parking_station = name_parking_station;
    this.km_made = km_made;
}

// In your line reader loop:
// lineRead contains the current line
var lineParts = lineRead.Split(' ').Where(item => !string.IsNullOrWhiteSpace(item)).ToArray();        

// lineParts now should contain 3 strings

if(lineParts.Length == 3)
{
    var bicycle = new Bicycle(int.Parse(lineParts[0]), lineParts[1], int.Parse(lineParts[2]));
    // add your new object to a collection of Bicycle objects
}

为了简单起见,省略了数据验证。我建议你使用 int.TryParse()。 如果我对行格式的假设不正确,请告诉我。 您希望如何在 ListView 中显示您的 Bicycle 对象?

【讨论】:

    【解决方案2】:

    您可以控制文本文件格式吗?如果是这样,您可以使用开箱即用的序列化。 You could also build your own custom serializer。也就是说,您可能需要重新考虑您的 readonly 属性,因为它不会序列化。

    From MSDN for standard XML Serialization:

    MySerializableClass myObject;
    // Construct an instance of the XmlSerializer with the type
    // of object that is being deserialized.
    XmlSerializer mySerializer = 
    new XmlSerializer(typeof(MySerializableClass));
    // To read the file, create a FileStream.
    FileStream myFileStream = 
    new FileStream("myFileName.xml", FileMode.Open);
    // Call the Deserialize method and cast to the object type.
    myObject = (MySerializableClass) mySerializer.Deserialize(myFileStream);
    

    【讨论】:

    • "也就是说,您可能需要重新考虑您的只读属性,因为它不会序列化。" - 或者编写一个序列化器而不是可以使用 ctor 的
    • json.net 序列化程序是有史以来下载次数最多的 nuget 包,它也可以处理 xml。我可以建议查一下。 @MurrayFoxcroft
    • Json.net 很棒。我坚持使用不需要 3rd 方包的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-11-29
    • 2022-06-14
    • 2013-06-27
    • 2017-11-03
    • 2011-05-24
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多