域不允许在C#中的接口 [英] fields not allowed in C# interface

查看:134
本文介绍了域不允许在C#中的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有相当多的在Java中的偏差和C#语言,其中一个我观察到的是,我们不能在一个界面中添加变量常量。从Java背景被我被莫名其妙地看到编译错误,当我尝试这样做。

There are quite a lot of deviations in Java and C# languages, one of which I observed was we cannot add variable constants in an interface. Being from Java background I got baffled to see compilation error when I tried this.

有谁有解释为什么是这样呢?

Does anyone has explanation why it is so?

推荐答案

一个字段是实现细节的一类,不应该暴露了它的接口。
接口是一种方法,一类抽象掉的实施细则。这两个概念看起来矛盾,真的不适合在一起。

A field is an implementation detail of a class and should not be exposed an its interface. An interface is a way to abstract away implementation details of a class. These two concepts look contradictory and don't really fit together.

您的可以的声明中,而不是接口的属性。

You can declare properties in interfaces instead.

UPDATE(实现后的问题是关于常量,而不是变量域):认为的(纯属我个人猜测)了Java决定允许这样的结构,因为它不具备枚举类型当时的情况。从一开始的C#已枚举和优选那些大部分时间常数。此外,您可以创建在C#中的静态类,并添加你喜欢它的一切,运沿界面没有任何真正的麻烦。支持这种结构只想让接口定义更为复杂。

UPDATE (after realizing the question was about constants, not variable fields): I think (purely my personal speculation) that Java decided to allow such a construct because it didn't have enum types back then. C# has had enums since the beginning and preferred those to constants most of the time. Moreover, you can create a static class in C# and add everything you like in it and ship it along the interface without any real hassles. Supporting such a construct would just make interface definitions more complicated.

这篇关于域不允许在C#中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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