c# – 重新转换为派生类型
发布时间:2020-12-16 01:44:53 所属栏目:百科 来源:网络整理
导读:我有一个问题,我不确定如何接近,我希望这里的人会有一些很好的建议. 我正在解析包含多个日志(每行一个日志)的文本文件.格式如下: Date Type Description10/20 A LogTypeADescription10/20 B LogTypeBDescription10/20 C LogTypeCDescription 在这里,您可以
我有一个问题,我不确定如何接近,我希望这里的人会有一些很好的建议.
我正在解析包含多个日志(每行一个日志)的文本文件.格式如下: Date Type Description 10/20 A LogTypeADescription 10/20 B LogTypeBDescription 10/20 C LogTypeCDescription 在这里,您可以看到有三种“类型”的日志(A,B和C).根据日志的类型,我将以不同方式解析“描述”字段. 我的问题是我应该如何设置数据结构? class Log { DateTime Date; String Type; String Description; public Log(String line) { Parse(line); } } class ALog : Log { } class BLog : Log { } class CLog : Log { } 现在,每个派生类都可以拥有自己的唯一属性,具体取决于“描述”字段的解析方式,并且它们仍将保留三个“核心”属性(日期,类型和描述). 到目前为止一切都很好,除非我从日志文件解析该行之前不知道我需要什么类型的(派生)日志.当然,我可以解析该行,然后弄清楚,但我真的希望解析代码在“Log”构造函数中.我希望我能做到这样的事情: 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(); } 但不幸的是,我不认为这是可能的. Log l = new Log(line); if(l.Type == "A") l = new ALog(); 要么是非法的,要么破坏我在第一次创建“Log”时所做的所有解析. 有什么建议? 解决方法
删除构造函数并将Parse更改为返回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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容