问题描述:

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.

网友答案:

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...

网友答案:

File class is just a container to group and organize a bunch of related methods for File IO. so what's your need exactly?

Read the Decorator Pattern to add additional functionality to the existing class.

相关阅读:
Top