【问题标题】:How to make a class act as another one如何让一个班级充当另一个班级
【发布时间】:2014-12-15 11:43:13
【问题描述】:

出于结构原因,我必须使我的文件管理类FileManagement 非静态。 因此我必须像这样使用它

FileManagement fm = new FileManagement();
fm.Save(10);

但我想静态使用它,比如

FileManagement.Save(10);

现在,我想创建一个额外的类,例如

public static class FileManager
{
    public static FileManagement Execute = new FileManagement();
}

现在我可以Filemanager.Execute.Save(10);

但是有没有办法让FileManager 的行为完全像FileManagement? 那么,我可以像FileManager.Save(10); 一样使用它吗?

【问题讨论】:

  • 让类中的静态方法可用,也许?
  • Static instances are for many considered to be harmful. 抱歉,这么多人是谁,为什么?只是好奇
  • 一个词:线程。
  • 这是因为它引入了全局状态,并且经常会使测试变得困难和不可能。正如 Nathan 指出的那样,线程化变成了一场噩梦。
  • 虽然我承认静态成员/方法带来的缺点,但请考虑一下。 Math 类中有很多静态方法。假设我们需要 Round 方法。如果没有静态方法,那么我们将不得不为该类创建一个仅包含一个方法的大量信息的实例,或者为了避免在堆中浪费不必要的大空间,我们必须将这个 Math 类分解为尽可能多的小部分可以,比如 Round、Abs、Sin 等的单独类。

标签: c# data-structures


【解决方案1】:

您可以尝试创建一个静态包装器:

public static class FileManagementWrapper {
  private static readonly FileManagement execute = new FileManagement();

  public static void Save(int i) {
    execute.Save(i);
  }

  // other methods...
}

【讨论】:

  • 就我而言,这将花费很多时间。
【解决方案2】:

这样

public static class FileManager
{
    public static void Save(int arg){
        execute.Save(arg);
    }
    private static FileManagement execute = new FileManagement();
}

【讨论】:

  • 如果您只将 FileManagement 中的方法委托给 FileManager,那么您应该考虑从接口继承两者。只要您不在 FileManager 中引入其他成员,那么我认为静态设计是可以的,因为您可以对您的 FileManagement 类进行单元测试。
猜你喜欢
  • 2018-07-24
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多