更新时间:2023-02-15 15:18:37
如果您正在使用派生类的实例,则没有基本实例
。
示例:
If you're working with an instance of the derived class, there is no base instance
.
An example:
class A
{
public void Foo() { ... }
}
class B : A
{
public void Bar() { ... }
}
在 B
中是不可能的:
public void Bar()
{
// Use of keyword base not valid in this context
var baseOfThis = base;
}
您可以执行以下操作:
public void Bar()
{
base.Foo();
}
您还可以添加另一种方法
And you can add another method like
public A GetBase()
{
return (A)this;
}
然后您可以
public void Bar()
{
var baseOfThis = GetBase();
// equal to:
baseOfThis = (A)this;
}
因此,此 GetBase()
方法可能就是您想要的。
So this GetBase()
method is probably what you want.
最重要的是:如果您有 B
的实例,继承了所有属性和 A
的非重写行为,但是它不包含 B
的实例( A 实例的引用。您可以将您的 B
实例转换为 A
,但是它仍然是 B的实例。
。
The punchline is: If you have an instance of B
, it inherits all properties and the non-overriden behaviour of A
, but it does not consist of an instance of B
which holds an (hidden but automatic) reference to an instance of A
. You can cast your B
instance to A
, but it remains to be an instance of B
.