Snæ*_*ørn 5 c# inheritance interface
我基本上IFoo
在Inherited类中定义了两次.这是否会导致一些不可预见的后果?
interface IFoo {
...
}
interface IBar : IFoo {
...
}
class Base : IFoo {
...
}
class Derived : Base, IBar {
...
}
Run Code Online (Sandbox Code Playgroud)
我想打的原因IBar
继承IFoo
的,所以我可以工作Derived
,因为它是IFoo
无需进行转换的.
if (Derived is IBar)
// Do work
Run Code Online (Sandbox Code Playgroud)
如果它不继承我必须施放它.这使得使用更复杂,并且类的用户可能不理解那IBar
只是一个专业化IFoo
.
if (Derived is IBar)
Derived as IFoo
// Do work
Run Code Online (Sandbox Code Playgroud)
这是不好的做法吗?这个问题有什么其他解决方案?
它不会在代码术语中引起任何不可预见的情况.这只是多余的.
至于这段代码:
if (Derived is IBar)
Derived as IFoo
Run Code Online (Sandbox Code Playgroud)
这是完全不必要的,因为Derived
是一个IFoo
,因为你的声明-所以不要这么做!
请注意,即使IBar
不是源自IFoo
,您仍然不需要Derived as IFoo
.鉴于:
interface IFoo {}
interface IBar {}
class Base : IFoo {}
class Derived : Base, IBar
{
}
Run Code Online (Sandbox Code Playgroud)
然后编译好了:
var derived = new Derived();
IBar bar = derived; // Fine.
IFoo foo = derived; // Also fine.
Run Code Online (Sandbox Code Playgroud)