无法解决密封类的最佳解决方法? [复制]

问题描述 投票:0回答:1

我正在制作一个处理数千个文件的程序。对于每个文件,我创建一个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;
    }
}

现在我的问题是:这是最好的方法吗?还有其他方法可以解决无法继承密封类的问题?

c# inheritance fileinfo sealed
1个回答
0
投票

您几乎正确地做到了,您的问题的解决方案是完全使用decorator pattern

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

查看这些帖子以获取更多详细信息:

1- decorator pattern

2- UnderstandingplusandplusImplementingplusDecoratorp

© www.soinside.com 2019 - 2024. All rights reserved.