如何从派生类中获取基类实例 [英] How to Get Base Class Instance from a Derived Class

查看:181
本文介绍了如何从派生类中获取基类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否可行,但是我试图从派生类中获取基类实例。在C#中,我可以使用 base 关键字访问基类的属性和方法(当然),但是我想使用 base 本身。尝试这样做会导致在此情况下使用关键字'base'无效 错误。

I don't know if this is possible, but I am trying to get the Base Class instance from a Derived Class. In C#, I can use the base keyword to access properties and methods of the Base Class (of course), but I want to use base itself. Attempting to do so results in a "Use of keyword 'base' is not valid in this context" error.

示例代码

public class SuperParent
{
    public int SPID;

    public SuperParent()
    {
    }
}

public class SubChild : SuperParent
{
    public SubChild(int pSPID)
    {
        base.SPID = pSPID;
    }

    public int BaseSPID
    {
        get
        {
            SuperParent sp = base;
            return sp.SPID;
        }
    }
}


推荐答案

如果您正在使用派生类的实例,则没有基本实例
示例:

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.

这篇关于如何从派生类中获取基类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆