2015-12-18 38 views
-2

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

适合[codereview](http://codereview.stackexchange.com/)更好。 – Sinatr

+1

也许你应该在http://codereview.stackexchange.com/上发布这个。 –

+1

为什么你必须使用'static'类? – Aron

回答

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; 
     } 
    } 
} 

至少现在,当你升级你的建筑,你会不会留下一堆难以维护/测试静,甚至更糟,那些拒绝实例化不止一次类。

+0

恩,谢谢你的努力。我不得不问,以便我可以说服自己,我没有忽略一些更简单的解决方案。如果没有重写,这个班不太可能改变......这次的差别是我想学点东西。 – Steinbitglis