简体   繁体   中英

What is the meaning of “: base” in the constructor definition?

What is the meaning of " : base " in the costructor of following class(MyClass) ? Please explain the concept behind constructor definition given below for class MyClass.

public class MyClass: WorkerThread
{
        public MyClass(object data): base(data) 
        { 
           // some code       

        }
}

public abstract class WorkerThread
{

        private object ThreadData;
        private Thread thisThread;

        public WorkerThread(object data)
        {
            this.ThreadData = data;
        }

        public WorkerThread()
        {
            ThreadData = null;
        }
}

The base class is WorkerThread. When you create a MyClass, a WorkerThread must be created, using any of its constructors.

By writing base(data) you are instructing the program to use one WorkerThread's constructor which takes data as a parameter. If you didn't do this, the program would try to use a default constructor - one which can be called with no parameters.

It calls the constructor of the class it inherits from, and provides the according arguments.

Sort of like calling

new WorkerThread(data)

It means you are passing the data parameter passed to the MyClass constructor through to the constructor of the base class (WorkerThread) in effect calling

public WorkerThread(object data)
{
    this.ThreadData = data;
}

A rare case where VB may be clearer...

Public Class MyClass
  Inherits WorkerThread

  Public Sub New(data)
    MyBase.New(data)
  End Sub

End Class

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