通过接口使用静态类? [英] Use static class by interface?
问题描述
想象一下,您需要从整个应用程序中访问一些方法。静态类是理想的。
imagine you have some methods you need to access from your whole application. A static class is ideal for this.
public static class MyStaticClass
{
public static void MyMethod()
{
// Do Something here...
}
}
但也许将来我会在另一个静态类中添加静态方法的第二个实现。
But maybe in future I'll add a second implementation of the static methods in another static class.
public static class MyStaticClass2
{
public static void MyMethod()
{
// Do Something here...
}
}
有没有办法更改我的其他代码中使用的静态类而不更改来自的调用MyStaticClass.MeMethod();
到 MyStaticClass2.MyMethod();
?
Is there a way to change static class used in my other code without changing the calls from MyStaticClass.MeMethod();
to MyStaticClass2.MyMethod();
?
I考虑一个界面,但我不知道如何实现这个...如果我说疯了,说出来,我只需更改电话:D
I thought about an interface but i have no idea how to implement this... If I'm talking crazy say it and I'll simply change the calls :D
推荐答案
你想要一个工厂模式
所以你的工厂是
public static MyStaticClassFactory
{
public static IMyNonStaticClassBase GetNonStaticClass()
{
return new MyNonStaticClass1();
}
}
实例
public class MyNonStaticClass1 : IMyNonStaticClassBase
{
//
}
接口
public interface IMyNonStaticClassBase
{
void MyMethod();
}
这篇关于通过接口使用静态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!