为什么静态类无法实现接口? [英] Why can static classes not implement interfaces?

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

问题描述

可能重复:结果
为何隐而不宣&rsquo的;?吨C#允许静态方法来实现接口

在我的应用我想用一个库,会做的原始数据访问(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);



没有它不必重新生成所有的时间。
,因为我希望我的资料库是可以互换的,我wnat他们实现一个共同的接口: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 +次,我鄙视库模式,了解了国际奥委会和实现我的问题是制定甚少。

UPDATE
Five years later: this question is visited 20k+ times, I despise 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天全站免登陆