C# - 如何包装静态类

发布于 2024-10-09 09:35:09 字数 93 浏览 0 评论 0原文

我想为 System.Io 创建 util 类(例如文件、目录等)。

由于无法对静态类进行继承,我想知道如何包装 System.Io.File 的正确方法。

I want to make util classes for System.Io (such as File, Directory etc).

Since inheritance cannot be done for static classes i want to know how would be a proper way to wrap lets say System.Io.File.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一场信仰旅途 2024-10-16 09:35:09

我将创建三种类型:

  • 包含您希望能够测试的所有方法等的接口,例如

    公共接口IFileSystem
    {
        Stream OpenWrite(字符串文件名);
        TextReader OpenText(字符串文件名);
        // ETC
    }
    
  • 委托给系统实现的实现:

    公共类 FrameworkFileSystem : IFileSystem
    {
        公共流OpenWrite(字符串文件名)
        {
            返回 File.OpenWrite(文件名);
        }
        // ETC
    }
    
  • 用于测试的假实现:

    公共类 FakeFileSystem : IFileSystem
    {
        // 可能有各种各样允许内存中文件的东西
        // 待创建等
    }
    

您可能不想将 File 中的所有内容放入其中 - 因为许多操作都可以组合从“核心”开始。当然,这意味着您自己重新实施操作,这可能是不可取的......

I would create three types:

  • An interface containing all the methods you want to be able to test etc, e.g.

    public interface IFileSystem
    {
        Stream OpenWrite(string filename);
        TextReader OpenText(string filename);
        // etc
    }
    
  • An implementation which delegates to the system implementation:

    public class FrameworkFileSystem : IFileSystem
    {
        public Stream OpenWrite(string filename)
        {
            return File.OpenWrite(filename);
        }
        // etc
    }
    
  • A fake implementation for testing:

    public class FakeFileSystem : IFileSystem
    {
        // Probably all kinds of things to allow in-memory files
        // to be created etc
    }
    

You may well not want to put everything from File in there though - as many of the operations can be composed from the "core" ones. Of course, that would mean reimplementing the operations yourself, which may be undesirable...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文