为什么静态类不实现接口? [英] Why can static classes not implement interfaces?
问题描述
可能重复:
为什么不使用静态方法实现接口?
在我的应用程序中,我想使用一个可以进行原始数据访问的存储库(TestRepository,SqlRepository,FlatFileRepository等)。
因为这样一个存储库将在我的应用程序的整个运行时间被使用,似乎是一个明智的事情,使我成为一个静态类,所以我可以去
In my application I want to use a Repository that will do the raw data access (TestRepository, SqlRepository, FlatFileRepository etc). Because such a repository would be used throughout the runtime of my application it seemed like a sensible thing to me to make it a static class so I could go
SqlRepository.GetTheThingById(5);
无需一直重新生成。
因为我希望我的存储库是可互换的,所以我们要实现一个通用的接口:IRepository。
但是当我尝试这样做,我得到
without it having to be regenerated all the time. Because I want my repositories to be interchangeable, I wnat them to implement a common interface: IRepository. But when I try to do so, I get
"Static classes cannot implement interfaces"
为什么不能?
你怎么建议我改变我的设计呢?有没有可以使用的模式?
Why can't they? How do you suggest I change my design then? Is there a pattern I could use?
更新
五年后:这个问题访问了20k +次,我了解了存储库模式的缺点,了解了IoC,意识到我的问题不好。
UPDATE
Five years later: this question is visited 20k+ times, I learned about the disadvantages of the repository pattern, learned about IoC and realise my question was poorly formulated.
我没有真正问到界面的C#规范是什么,而是为什么故意以这种特定的方式限制我。
I wasn't really asking what the C# specification of an interface is, rather why it was deliberately restricting me in this specific way.
实际答案是在实例或类型上调用方法的语法不同。但是问题是关闭的。
The practical answer is that the syntax for calling a method on an instance or on a type are different. But the question is closed.
推荐答案
接口不能有静态方法。实现接口的类需要将它们全部实现为实例方法。静态类不能有实例方法。 QED。
Interfaces can't have static methods. A class that implements an interface needs to implement them all as instance methods. Static classes can't have instance methods. QED.
这篇关于为什么静态类不实现接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!