C#继承 [英] C# inheritance
问题描述
让我们说我有下面的代码:
Let's say I have the following code:
interface ISomeInterface
{
void DoSomething();
void A();
void B();
}
public abstract class ASomeAbstractImpl : ISomeInterface
{
public abstract void A();
public abstract void B();
public void DoSomething()
{
// code here
}
}
public class SomeImpl : ASomeAbstractImpl
{
public override void A()
{
// code
}
public override void B()
{
// code
}
}
的问题是,我希望有密封 ASomeAbstractImpl.DoSomething()
方法(最终),所以没有其他的类都可以实现它。
作为代码现在是 SomeImpl
可以有一个调用方法 DoSomething的()
键,可以被称为(它不会覆盖从抽象类的同名方法,因为这是没有标记为虚拟的),但我想切断 SomeImpl $ C $实施这种方法的可能性C>类。
The problem is that i wish to have the ASomeAbstractImpl.DoSomething()
method sealed (final) so no other class could implement it.
As the code is now SomeImpl
could have a method called DoSomething()
and that could be called (it would not override the method with the same name from the abstract class, because that's not marked as virtual), yet I would like to cut off the possibility of implementing such a method in SomeImpl
class.
这可能吗?
推荐答案
方法对C#默认情况下密封。有,然而,什么可以做,以防止方法隐藏(暴露在派生类中具有相同名称的方法,常用的有新
)
Methods in C# are sealed by default. There is, however, nothing you can do to prevent method hiding (exposing a method with the same name in the derived class, commonly with new
).
或者,对于这个问题,接口重新实现:
Or, for that matter, interface-reimplementation:
static void Main()
{
ISomeInterface si = new EvilClass();
si.DoSomething(); // mwahahah
}
public class EvilClass : ASomeAbstractImpl, ISomeInterface
{
public override void A() {}
public override void B() { }
void ISomeInterface.DoSomething()
{
Console.WriteLine("mwahahah");
}
}
这篇关于C#继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!