I have 2 classes, one "Bicycle" and one "User". The first one has the following attributes:
private readonly int codeB;
private string name_parking_station;
int km_made;
and the second one:
private string name;
private int codeB;
private int utilization_duration;
Both classes have constructors with parameters and getters/setters. My question is: how do I instantiate objects from both classes with data from text files for which I've created? And also, how do I add them to 2 different ListView-s?
Do you have control over the text file format? If so, you can use out of the box serialization. You could also build your own custom serializer . That said, you may need to rethink your readonly
property as this will not serialize.
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);
If your Bicycle lines don't contain those '//' parts, just your data, it's easy to create Bicycle objects by reading the file line by line and process the lines like this:
// 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
}
Data validation is left out to keep things simple. I suggest you use int.TryParse(). Let me know if my assumption about the line format is not correct. How exactly would you like to present your Bicycle objects in a ListView?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.