Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 6 MORE ABOUT CLASSES

Instance Constructors

An instance constructor is a special method that is executed whenever a new instance of a class is created.

A constructor is used to initialize the state of the class instance.

If you want to be able to create instances of your class from outside the class, you need to declare the constructor public.

Figure 6-12 shows the syntax of a constructor. A constructor looks like the other methods in a class declaration, with the following exceptions:

The name of the constructor is the same as the name of the class.

A constructor cannot have a return value.

Figure 6-12. Constructor declaration

For example, the following class uses its constructor to initialize its fields. In this case, it has a field called TimeOfInstantiation that is initialized with the current date and time.

class MyClass

 

{

 

DateTime TimeOfInstantiation;

// Field

...

 

public MyClass()

// Constructor

{

 

TimeOfInstantiation = DateTime.Now;

// Initialize field

}

 

...

 

}

 

 

 

Note Having finished the section on static properties, take a closer look at the line that initializes

TimeOfInstantiation. The DateTime class is from the BCL, and Now is a static property of the DateTime class. The Now property creates a new instance of the DateTime class, initializes it with the current date and time from the system clock, and returns a reference to the new DateTime instance.

133

CHAPTER 6 MORE ABOUT CLASSES

Constructors with Parameters

Constructors are like other methods in the following ways:

A constructor can have parameters. The syntax for the parameters is exactly the same as for other methods.

A constructor can be overloaded.

When you use an object-creation expression to create a new instance of a class, you use the new operator followed by one of the class’s constructors. The new operator uses that constructor to create the instance of the class.

For example, in the following code, Class1 has three constructors: one that takes no parameters, one that takes an int, and another that takes a string. Main creates an instance using each one.

class Class1

 

 

 

 

 

{

 

 

 

 

 

 

int Id;

 

 

 

 

 

 

string

Name;

 

 

 

 

 

public

Class1()

{ Id=28;

Name="Nemo"; }

// Constructor 0

public

Class1(int val)

{ Id=val;

Name="Nemo"; }

// Constructor 1

public

Class1(String name) { Name=name;

}

// Constructor 2

public

void SoundOff()

 

 

 

 

 

{ Console.WriteLine("Name {0},

Id {1}", Name, Id); }

 

 

}

 

 

 

 

 

 

class Program

 

 

 

 

 

{

 

 

 

 

 

 

static

void Main()

 

 

 

 

 

{

 

 

 

 

 

 

Class1 a = new Class1(),

 

 

// Call constructor 0.

 

b = new Class1(7),

 

// Call constructor 1.

 

c = new Class1("Bill");

 

// Call constructor 2.

a.SoundOff();

 

 

 

 

 

b.SoundOff();

 

 

 

 

 

c.SoundOff();

 

 

 

 

 

}

 

 

 

 

 

 

}

 

 

 

 

 

 

This code produces the following output:

 

 

 

 

 

 

 

 

 

 

Name Nemo,

Id 28

 

 

 

 

 

Name Nemo,

Id 7

 

 

 

 

 

Name Bill,

Id 0

 

 

 

 

 

 

 

 

 

 

 

 

134

CHAPTER 6 MORE ABOUT CLASSES

Default Constructors

If no instance constructor is explicitly supplied in the class declaration, then the compiler supplies an implicit, default constructor, which has the following characteristics:

It takes no parameters.

It has an empty body.

If you declare any constructors at all for a class, then the compiler does not define a default constructor for the class.

For example, Class2 declares two constructors.

Because there is at least one explicitly defined constructor, the compiler does not create any additional constructors.

In Main, there is an attempt to create a new instance using a constructor with no parameters. Since there is no constructor with zero parameters, the compiler produces an error message.

class Class2

 

 

{

 

 

public Class2(int Value)

{ ... }

// Constructor 0

public Class2(String Value) { ... }

// Constructor 1

}

 

 

class Program

 

 

{

 

 

static void Main()

 

 

{

 

 

Class2 a = new Class2();

// Error! No constructor with 0 parameters

...

 

 

}

 

 

}

 

 

135

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]