为什么静态类不能实现接口? [英] Why static classes cant implement interfaces?

查看:241
本文介绍了为什么静态类不能实现接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在我的应用程序中,我想使用一个进行原始数据访问的存储库( 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 want 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆