I have a problem that I'm not sure how to approach, and I'm hoping the people here will have some good tips.
I am parsing text files, which contain several logs (one log per line). The format is something like the following:
Date Type Description
10/20 A LogTypeADescription
10/20 B LogTypeBDescription
10/20 C LogTypeCDescription
Here, you can see there are three "types" of logs (A, B, and C). Depending on what type the log is, I will parse the "Description" field differently.
My question is how should I set up the data structure? I would like to do something like this:
class Log
{
DateTime Date;
String Type;
String Description;
public Log(String line)
{
Parse(line);
}
}
class ALog : Log { }
class BLog : Log { }
class CLog : Log { }
Now, each derived class can have its own unique properties, depending on how the "Description" field is parsed, and they will still maintain the three "core" properties (Date, Type, and Description).
Everything is good so far, except I don't know what type of (derived) log I need until I have parsed the line from the log file. Of course, I could parse the line, and then figure it out, but I really want the parsing code to be in the "Log" constructor. I wish I could do something like this:
void Parse(String line)
{
String[] pieces = line.Split(' ');
this.Date = DateTime.Parse(pieces[0]);
this.Type = pieces[1];
this.Description = pieces[2];
if(this.Type == "A")
this = new ALog();
else if(this.Type == "B")
this = new BLog();
else if(this.Type == "C")
this = new CLog();
}
But unfortunately I don't think this is possible. I haven't tried yet, but I'm pretty sure doing this:
Log l = new Log(line);
if(l.Type == "A") l = new ALog();
Would either be illegal or destroy all of the parsing I did when I first created the "Log."
Any suggestions?
Remove the constructor and change Parse to a static that returns a Log.
static Log Parse(string line)
{
string[] tokens line.Split(' ');
var log = null;
if (tokens[1] == "A") log = new ALog();
else if (tokens[1] == "B") log = new BLog();
else log = new CLog();
log.Date = tokens[0];
log.Description = tokens[1];
return log;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With