我遇到了一个很难解释的问题。考虑3类; A、B 和 C。以下继承代码是 C# 伪代码:
class A
{
public int x1 { get; set;}
public int x2 { get; set;}
}
class B : A
{
public Property SomeProperty
{
get
{
return new Property(base.x1, base.x2);
}
set
{
base.x1 = value.x1;
base.x2 = value.x2;
}
}
}
class C : B
{
public Property SomeProperty
{
get
{
return base.SomeProperty;
}
set
{
base.SomeProperty = new Property(value.x1 * 2, value.x2 * 2);
}
}
}
请注意,A 类和 B 类的源代码无法更改。 我正在开发的模块包含 C 类的声明和定义。因此,如果我必须更改任何内容,则必须在 C 类中进行更改。
该模块的主要问题之一是有 200 多个函数,如下所示:
function (A objOfA)
{
objOfA.x1 = 2;
objOfA.x2 = 3;
}
function1()
{
function(new C());
}
上述函数调用产生的问题是,派生类 C 中编写的任何内容都被完全绕过,因为 objOfA 的类型是 A。不幸的是,我无法更改这些函数,因为许多模块都依赖于这些函数。
有没有一种方法,即使对象的类型是A,也可以调用C的函数?
最佳答案
So is there a way such that even if the type of the object is A, functions of C are the ones being called?
实现这一点的方法是使这些成员虚拟
,然后在派生类型中覆盖
它们。但是,它们需要在基类中声明为虚拟的,才能成为一个选项。无法覆盖非虚拟成员。
关于c# - 如何避免类继承绕过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31034039/