我有 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?
最佳答案
您可以控制文本文件格式吗?如果是这样,您可以使用开箱即用的序列化。 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);
关于c# - 使用文本文件中的数据初始化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37829451/