我有一个代表rtf文件ClsRtfDoc
的类。
实例化ClsRtfDoc
对象读取rtf文件,它首先解析rtf文件以获取各种rtf文件元数据。
例如,我有一个字段int paperHeight
,我用它来存储从保存rtf文件内容的字符串解析的rtf文件纸高度。
由于rtf文件内容在字符串变量中,因此PaperHeight
属性数据类型是字符串,PaperHeight
属性setter
从字符串blob解析纸张高度(例如,查找\paperw12240\paperh15840
并从blob中获取15840),将其转换为整数,并将paperHeight
字段设置为整数值。见下面的代码。
我以这种方式构造代码,因为我想隔离parse + set操作。我是否通过使属性数据类型与相应字段的数据类型不匹配来滥用属性设置器的概念?是否有更好的实践(设计模式?)我应该用于构建此代码?
码
public partial class ClsRtfDoc
{
int paperHeight;
public string PaperHeight
{
set
{
MatchCollection objPaperHeight = Regex.Matches(value, "(\\\\paperw\\d+)(\\\\paperh\\d*)");
if (objPaperHeight.Count >= 1 && objPaperHeight[0].Groups.Count == 3)
{
if (!(Int32.TryParse((objPaperHeight[0].Groups[2].Value).Replace("\\paperh", ""), out int paperHeightValue)))
{
throw new FormatException("Can't find paper height");
}
else
{
paperHeight = paperHeightValue;
}
}
else
{
throw new FormatException("Can't find paper height");
}
}
}
// CTOR
public ClsRtfDoc(string fqFRtfFileName)
{
string rtfTextFromFile = GetRtfFromFile(fqFRtfFileName);
PaperHeight = rtfTextFromFile;
}
}
我不认为这是实现这种逻辑的最佳方式,原因有很多。最明显的一点是,你的班级有很多理由要改变,因此违反了单一责任原则。我建议你创建一个“解析”服务,为你完成这项工作,然后将输出交给ClsRtfDoc
。因为正如其名称所示,ClsRtfDoc
在被解析为实际的ClsRtfDoc
后代表该文档。
例如,正确的ClsRtfDoc
可能如下所示:
public class ClsRtfDoc
{
public int PaperHeight {get;set;}
public ClsRtfDoc(int paperHeight)
{
this.PaperHeight = paperHeight;
}
public void AddPaper(){
//Do something
}
public void RemovePaperAt(int index){
}
}
您可能期望在ClsRtfDoc
对象上看到的“方法”示例是AddPaper
或RemovePaperAt
。但另一方面,解析服务可能看起来像这样:
public interface IClsRtfDocParser
{
ClsRtfDoc ParseFromFile(string filePath);
}
public class ClsRtfDocParser:IClsRtfDocParser
{
public ClsRtfDoc ParseFromFile(string filePath)
{
int paperHeight = 0;
//After reading the metadata, you reach the paper height line or something like that
MatchCollection objPaperHeight = Regex.Matches(value, "(\\\\paperw\\d+)(\\\\paperh\\d*)");
if (objPaperHeight.Count >= 1 && objPaperHeight[0].Groups.Count == 3){
if (!(Int32.TryParse((objPaperHeight[0].Groups[2].Value).Replace("\\paperh", ""), out int paperHeightValue)))
{
throw new FormatException("Invalid file format");
}
else
{
paperHeight = paperHeightValue;
}
}
return new ClsRtfDoc(paperHeight);
}
}
我不会说你滥用它,因为setter将它转换为正确的数据类型。这可能不是最好的做法。如果我是你,我会制作一个方法来完成你在setter中所做的事情,然后让setter设置Int值,但我不认为你拥有的是“错误”。