防止任何子类覆盖/隐藏方法 c#;保留超类的方法签名
本文关键字:方法 保留 超类 子类 任何 覆盖 隐藏 | 更新日期: 2023-09-27 18:32:15
我的问题属于这种情况
class A
{
public virtual void show()
{
Console.WriteLine("Hey! This is from A;");
}
}
class B:A
{
public sealed override void show()
{
Console.WriteLine("Hey! This is from B;");
}
}
class C:B
{
public new void show()
{
Console.WriteLine("Hey! This is from C;");
}
}
或
class A
{
public void show()
{
Console.WriteLine("Hey! This is from A;");
}
}
class B:A
{
public new void show()
{
Console.WriteLine("Hey! This is from B;");
}
}
在上面的代码中,C 类隐藏了 B 类的方法 Show()
问。我如何确定没有子类覆盖和隐藏方法 已在超类中定义
像这样的东西或可能是类似于readonly
用于字段的关键字
class A1
{
public sealed void show() // I know it will give compilation error
{
Console.WriteLine("Hey! This is from A1");
}
}
class B1 : A1
{
public void show()
{
Console.WriteLine("You must get a compilation Error if you create method with this name and parameter");
}
}
有没有这样的关键词?
编辑 1:
是的,我想阻止扩展器以确保它使用正确的 使用方法名称和参数 coz 实现(如果其他人) 查看代码应该是正确的
防止存在隐藏
该方法的子类的唯一方法是使类sealed
,从而防止任何子类。 如果可以有任何子类,那么它们可以隐藏方法,而你对此无能为力。
如果您依赖于A
并且B
没有覆盖他们的方法,sealed
就可以完成这项工作。如果要防止方法隐藏,请确保所有需要 A
或继承者的成员都定义为 A
或 B
。
请考虑以下事项:
A a = new A();
a.show(); // "Hey! This is from A;"
A a = new B();
a.show(); // "Hey! This is from B;"
B b = new B();
b.show(); // "Hey! This is from B;"
A a = new C();
a.show(); // "Hey! This is from B;"
B b = new C();
b.show(); // "Hey! This is from B;"
只有当您将C
称为C
时,new
关键字才会发挥作用。
C c = new C();
c.show(); // "Hey! This is from C;"
总之,您的实现应仅使用将A
和B
的实例定义为A
或B
。事实上,除非在你的程序集中实现了类似C
的东西,否则你的代码不能被强制调用C
的public new void show()
。