我是否是通过让属性数据类型与相应字段的数据类型匹配来滥用属性转换器的概念



我有一个代表RTF文档ClsRtfDoc的类。

实例化ClsRtfDoc对象读取RTF文件,然后首先解析RTF文件以获取各种RTF文件元数据。

例如,我有一个字段int paperHeight,用于存储从包含RTF文件内容的字符串中排除的RTF文件纸高度。

由于RTF文件内容位于字符串变量中,因此PaperHeight属性数据类型是字符串,PaperHeight属性setter从字符串blob中解析纸的高度(例如,查找paperw12240paperh15840,从blob中查找15840),转换converts将其设置为整数,并将paperHeight字段设置为整数值。请参阅下面的代码。

我以这种方式构造了代码,因为我想隔离解析 设置操作。我是否是通过让属性数据类型与相应字段的数据类型不匹配来滥用属性转换器的概念?我应该在构建此代码时使用更好的练习(设计模式吗?)?

代码

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对象上看到的"方法"的示例是AddPaperRemovePaperAt。但是,另一方面的解析服务可能看起来像这样:

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);
    }
}

我不会说您正在滥用它,因为设置器将其转换为正确的数据类型。这可能不是最好的做法。如果我是你,我会做一种做你在二传手中的方法,然后离开设置器来设置int值,但我认为您没有"错误"。

最新更新