【问题标题】:How do I share code between static classes? [duplicate]如何在静态类之间共享代码? [复制]
【发布时间】:2016-03-25 04:31:13
【问题描述】:

我有两个非常相似的静态类,我认为它们应该共享相同的代码库,但我一直遇到 c# 的限制。

接口不能声明静态方法,静态方法不能是虚拟的等等。

最终我只想要一个更好看的版本:

public class StaticCoroutine {
    private static MonoBehaviour runner;

    public static void Start(IEnumerator coroutine) {
        if (runner == null) {
            runner = new GameObject("[Static Coroutine Runner]").AddComponent<StaticCoroutineRunner>();
        }
        runner.StartCoroutine(coroutine);
    }

    public static void Stop(IEnumerator coroutine) {
        if (runner != null) runner.StopCoroutine(coroutine);
    }
}

public class StaticCoroutineInfinite {
    private static MonoBehaviour runner;

    public static void Start(IEnumerator coroutine) {
        if (runner == null) {
            runner = new GameObject("[Static Coroutine Infinite Runner]").AddComponent<StaticCoroutineRunner>();
            Object.DontDestroyOnLoad(runner.GameObject);
        }
        runner.StartCoroutine(coroutine);
    }

    public static void Stop(IEnumerator coroutine) {
        if (runner != null) runner.StopCoroutine(coroutine);
    }
}

【问题讨论】:

  • 更适合codereview
  • 也许你应该在codereview.stackexchange.com上发帖
  • 从假设出发,尽量避免静态。在大多数情况下,没有理由使用它们。这样做将使您的代码更加模块化和可测试。
  • @SBI 我见过很多烂代码库,它们源于“有人在我之前做过这件事,所以让我们继续做下去”的心态。
  • 继承在设计上不适用于静态类,请参阅stackoverflow.com/questions/774181/…

标签: c# oop


【解决方案1】:

您坚持认为这仍然是静态的,看来您只是在推翻旧的单身难题。 static 是模块化的敌人。

我真的不建议这样做...您应该将服务作为可以注入的依赖项提供,即使您不使用 IoC/DI。

假设您现在不想完全重构,我建议将所有功能移到可实例化的类中,并为该类的实例提供静态访问器。

 public class MyThing : SomeBaseClass, ICanImplementInterfaces
 {
     private Lazy<MyThing> myThingLazy = new Lazy<MyThing>(() => new MyThing())
     public static MyThing Instance
     {
         get
         {
             return myThingLazy.Value;
         }
     }
 }

至少现在,当您升级架构时,不会留下一堆难以维护/测试的静态变量,或者更糟糕的是,拒绝实例化多次的类。

【讨论】:

  • 好吧,感谢您的努力。我不得不问,这样我才能说服自己我没有忽略一些更简单的解决方案。这门课如果不重写就不太可能改了……这次的不同是我想学点东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 2019-11-11
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
相关资源
最近更新 更多