Книга: C# 2008 Programmer

Calling Base Class Constructors

Calling Base Class Constructors

Suppose BaseClass contains two constructors — one default and one parameterized:

public class BaseClass {
 //---default constructor---
 public BaseClass() {
  Console.WriteLine("Default constructor in BaseClass");
 }
 //---parameterized constructor---
 public BaseClass(int x) {
  Console.WriteLine("Parameterized Constructor in BaseClass");
 }
}

And DerivedClass contains one default constructor:

public class DerivedClass : BaseClass {
 //---default constructor---
 public DerivedClass() {
  Console.WriteLine("Constructor in DerivedClass");
 }
}

When an instance of the DerivedClass is created like this:

DerivedClass dc = new DerivedClass();

The default constructor in BaseClass is first invoked followed by the DerivedClass. However, you can choose which constructor you want to invoke in BaseClass by using the base keyword in the default constructor in DerivedClass, like this:

public class DerivedClass : BaseClass {
 //---default constructor--- 
 public DerivedClass(): base(4) {
  Console.WriteLine("Constructor in DerivedClass");
 }
}

In this example, when an instance of the DerivedClass is created, the parameterized constructor in BaseClass is invoked first (with the argument 4 passed in), followed by the default constructor in DerivedClass. This is shown in the output:

DerivedClass dc = new DerivedClass();
//---prints out:---
//Parameterized Constructor in BaseClass
//Constructor in DerivedClass

Figure 6-7 shows that IntelliSense lists the overloaded constructors in BaseClass.


Figure 6-7 

Оглавление книги


Генерация: 2.141. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз