如何在静态类之间共享代码?

时间:2015-12-18 12:46:14

标签: c# oop

我有两个非常相似的静态类,我相信应该共享相同的代码库,但我一直在运行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);
    }
}

0 个答案:

没有答案