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
精彩评论