简体   繁体   中英

How to pass a base class as input parameter to the constructor of the derived class?

I have a derived class which is derived from base class,

public class DerivedClass : BaseClass
{
    public DerivedClass () {}
    public DerivedClass ( BaseClass bc )
    {
        // The following line is invalid, but I want to achieve something like this
        this = bc;
        // Error: (this) Cannot assign <This> because this is read only 
        // Error2: (bc) Cannot implicitly convert Type `BaseClass` to `DerivedClass`
    }
}

public class BaseClass
{
    public string TestName { get; set; }
    public uint TestNumber { get; set; }

    public BaseClass () { }
}

then from the Main method,

static void Main ( string[] args )
{
     BaseClass bc = new BaseClass ();
     bc.TestName = "dummy test";
     bc.TestNumber = 007;

     DerivedClass dc = new DerivedClass ( bc );
 }

Now my questions are,

  1. How to assign base class properties with the derived class, please note it has to achieved through the constructor of the derived class(shown in the code : this = bc; )?
  2. Is it a right coding practice, if not why?

Thanks!

this is read-only alias - remember to future you can do like this

public class DerivedClass : BaseClass
{
    public DerivedClass () {}
    public DerivedClass ( BaseClass bc )
    {
        TestName=bc.TestName;
        TestNumber=bc.TestNumber;
    }
}

Is it a right coding practice, if not why? Depends in what you try achieve

You cannot do that, you can't use this in the constructor which refers to the current instance because you're going to construct the object just now. I'd provide appropriate constructors:

public class DerivedClass : BaseClass
{
    public DerivedClass() { }
    public DerivedClass(string TestName, uint TestNumber)
    {
        base.TestName = TestName;
        base.TestNumber = TestNumber;
    }
    public DerivedClass(BaseClass bc) : this(bc.TestName, bc.TestNumber) { }
}

So if you're not using the BaseClass variable in your example at all you don't need it. It's pointless to create a base object just to initialize a child class object.

It's a bad practice.

That would mean your base class already represents whatever the derived class would be.

I'd recommend composition:

public class TestData
{
    public string TestName { get; set; }
    public uint TestNumber { get; set; }
}

public class BaseClass
{
    protected TestData data;
    public BaseClass(TestData data)
    {
        this.data = data;
    }
}

public class DerivedClass : BaseClass
{
    public DerivedClass(TestData data)
       : base(data)
    {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM