【问题标题】:Best workaround for not being able to inherit a sealed class? [duplicate]无法继承密封类的最佳解决方法? [复制]
【发布时间】:2019-10-02 17:04:04
【问题描述】:

我正在制作一个处理数千个文件的程序。我为每个文件创建一个 FileInfo 实例,但我缺少一些我需要的方法和属性。

我想通过从 FileInfo 继承来创建自己的自定义 FileInfo 类,但是该类是密封的,所以我不能。

我考虑为 FileInfo 制作扩展方法,但这看起来很难看,并且需要我在处理时多次运行相同的代码。 因此,我想出了一个“包装” FileInfo 类的自定义类。

这是其中的一部分:

class MyFileInfo
{
    FileInfo _fileInfo;

    // wrapper of existing property
    public string Name { get { return _fileInfo.Name; } }

    // custom property
    public string NameWithoutExtension { get; private set; }

    // custom property
    public string Increment { get; private set; }

    public MyFileInfo(string filePath)
    {
        _fileInfo = new FileInfo(filePath);

        NameWithoutExtension = GetNameWithoutExtension();
        Increment = GetIncrement();
    }

    private string GetNameWithoutExtension()
    {
        return _fileInfo.Name.Replace(_fileInfo.Extension, string.Empty);
    }

    private string GetIncrement()
    {
        return Regex.Match(NameWithoutExtension, @" #?\d{1,4}$").Value;
    }
}

现在我的问题是:这是最好的方法吗?如果不能继承密封类,还有什么办法可以解决?

【问题讨论】:

  • 您能解释一下您在使用扩展方法时遇到的问题吗?
  • 使用扩展方法我会多次调用它们,从而多次运行相同的代码。而如果我有一个类,我可以做所有我需要做的事情,并且只在构造函数中设置一次自定义属性,这似乎更有效。
  • 是有道理的,如果它发生得足够多以至于有明显的开销。顺便说一句,有一个Path.GetFilenameWithoutExtension() method,它会比你在那里得到的更安全并且可能更快。回答(我认为是)你的问题的实质:在我看来,你正在做的事情是一种用内存换周期的明智方式,但是当你优化时,分析一切以确保你正在攻击真正的问题并有效地做到这一点。

标签: c# inheritance fileinfo sealed


【解决方案1】:

你做的差不多了,解决你问题的方法就是使用decorator pattern

装饰器模式是一种设计模式,它允许行为 静态或动态添加到单个对象, 不会影响同一类中其他对象的行为。

查看这些帖子了解更多详情:

1-UnderstandingplusandplusImplementingplusDecoratorp

2-benefiting-with-the-decorator-pattern

【讨论】:

  • 感谢您的帮助!我想我现在理解了装饰器模式,但我还不确定为什么我应该在上面提到的解决方案上使用它。使用装饰器,我将创建一个或多个具有我想要添加的功能的新类,然后将它们链接到 FileInfo 的实例化中,对吗?例如:FileInfo fileInfo = new FileInfo().ExtensionClass()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-20
  • 2020-03-29
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 2010-11-20
  • 1970-01-01
相关资源
最近更新 更多