How to Get Base Class Instance from a Derived Class

戏子无情 提交于 2020-01-01 08:05:42

问题


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.

Example Code

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;
        }
    }
}

回答1:


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() { ... }
}

What is not possible within B:

public void Bar()
{
    // Use of keyword base not valid in this context
    var baseOfThis = base; 
}

You can do something like this:

public void Bar()
{
    base.Foo();
}

And you can add another method like

public A GetBase()
{
    return (A)this;
}

And then you can

public void Bar()
{ 
    var baseOfThis = GetBase();
    // equal to:
    baseOfThis = (A)this;
}

So this GetBase() method is probably what you want.

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.




回答2:


Well you not provide code for your question, but i supsect you want something like

class Base
{
    public virtual void Foo()
    {
        Console.WriteLine("base");
    }
}

class Derived : Base
{
    public override void Foo()
    {
        Console.WriteLine("derived");
    }

    //// bad
    //public Base MyBase
    //{
    //    get
    //    {
    //        return base; // Use of keyword 'base' is not valid in this context
    //    }
    //}

    // work but...
    public Base MyBase
    {
        get
        {
            return (Base)this;
        }
    }
}

But keep in mind that MyBase is really of type Derived

new Derived().MyBase.Foo(); // output "derived"



回答3:


the problem hasn't been explained as clearly as it could. however, typically, you may be better to use an abstract base class and methods and then override the required methods. you can then use the base.method as required in this case (otherwise you'll have just spun up an instance of the derived class).

public abstract class foo {

   public virtual void bar(){..}
}

public class footwo : foo {
   public override void bar(){
       // do somethng else OR:
       return base.bar();
   }
}

}




回答4:


The derived instance IS the base instance. It's just one object instance in memory.

example:

public class A : B 
{
}

var thing = new A();

thing is an instance of an A, and is also an instance of a B.
You could for example, write this line:
B thing2 = thing;




回答5:


Point 1: if you want to create the base class instance within child class than it does not worth. You already have public things accessible in child.

Point 2: If you have initialized child class and now want to get base class "instance" then how can you get that if it's not initialized(Because now the base class instance is not present in the physical memory, and there is just child class instance there)?




回答6:


I interpreted what they were asking a bit differently than the other answers here so I figured I would offer my $0.02.

// Create a "Parent" class that has some attributes.
public class Parent
{
    public string attribute_one { get; set; }
    public string attribute_two { get; set; }
    public string attribute_three { get; set; }
}

// Define a class called "Child" that inherits the
// attributes of the "Parent" class.
public class Child : Parent
{
    public string attribute_four { get; set; }
    public string attribute_five { get; set; }
    public string attribute_six { get; set; }
}

// Create a new instance of the "Child" class with
// all attributes of the base and derived classes.
Child child = new Child {
    attribute_one = "interesting";
    attribute_two = "strings";
    attribute_three = "to";
    attribute_four = "put";
    attribute_five = "all";
    attribute_six = "together";
};

// Create an instance of the base class that we will
// populate with the derived class attributes.
Parent parent = new Parent();

// Using reflection we are able to get the attributes
// of the base class from the existing derived class.
foreach(PropertyInfo property in child.GetType().BaseType.GetProperties())
{
    // Set the values in the base class using the ones
    // that were set in the derived class above.
    property.SetValue(parent, property.GetValue(child));
}

The result is a new object populated with the base class properties of the child class.




回答7:


 class Parent
 {
      private Parent _parent;
      public Parent()
      {
         _parent = this;
      }

     protected Parent GetParent()
     {
         return _parent;
     }
 }

class Child : Parent
{
    private Parent _parent;
    public Child()
    {
        _parent = base.GetParent();
    }
}


来源:https://stackoverflow.com/questions/19243057/how-to-get-base-class-instance-from-a-derived-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!