C# 接口 - 只在其他接口中实现一个接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2283432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Interfaces- only implement an interface in other interfaces
提问by Kukks
I would like to only implement certain interfaces within other interfaces, I don't want them to be able to be inherited directly by a class.
我只想在其他接口中实现某些接口,我不希望它们能够被类直接继承。
Thanks in advance!
提前致谢!
采纳答案by thecoop
You can't do this in C# - any class can implement any interface it has access to.
你不能在 C# 中做到这一点 - 任何类都可以实现它可以访问的任何接口。
Why would you want to do this? Bear in mind that by declaring an interface inheritance:
你为什么想做这个?请记住,通过声明接口继承:
public interface InterfaceA {}
public interface InterfaceB : InterfaceA {}
You're specifying that anything implementing InterfaceB
also has to implement InterfaceA
, so you'll get classes implementing InterfaceA
anyway.
您指定任何实现InterfaceB
也必须实现InterfaceA
,因此InterfaceA
无论如何您都会实现类。
回答by James Curran
The best I can suggest is to put them -- both the top level and the descended interfaces, in a separate assembly, with the base-level interfaces declared as internal
, and the interfaces which extend those interfaces as public
.
我能建议的最好方法是将它们——顶层接口和后代接口都放在一个单独的程序集中,基本级接口声明为internal
,而扩展这些接口的接口为public
。
回答by Tesserex
First of all, it doesn't make sense to say "implement within other interfaces" because interfaces can't implement anything.
首先,说“在其他接口内实现”是没有意义的,因为接口不能实现任何东西。
I can see two flawed ways of doing this, sort of.
我可以看到两种有缺陷的方法。
Make Animated and NonAnimated abstract classes that implement IAnimation. The concrete class below them can still forcibly override your IAnimation methods with the new operator:
class SomeAnim : Animated { public new void Foo() { } }
Use mixins. Keep IAnimated and INonAnimated as interfaces, but don't put any methods in your interface. Instead define extension methods like this:
static class Ext { public static void Foo(this IAnim anim) { if (anim is IAnimated) // do something else if (anim is INonAnimated) // do something else } }
制作实现 IAnimation 的 Animated 和 NonAnimated 抽象类。它们下面的具体类仍然可以使用 new 运算符强制覆盖您的 IAnimation 方法:
class SomeAnim : Animated { public new void Foo() { } }
使用混合。保持 IAnimated 和 INonAnimated 作为接口,但不要在你的接口中放置任何方法。而是像这样定义扩展方法:
static class Ext { public static void Foo(this IAnim anim) { if (anim is IAnimated) // do something else if (anim is INonAnimated) // do something else } }
again, a bit of a hack. But what you're trying to do indicates design flaws anyway.
再次,有点黑客。但是无论如何,您尝试做的事情都表明存在设计缺陷。