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

CHAPTER 18 CONVERSIONS

User-Defined Conversions

Besides the standard conversions, you can also define both implicit and explicit conversions for your own classes and structs.

The syntax for user-defined conversions is shown following.

The syntax is the same for both implicit and explicit conversion declarations, except for the keywords implicit and explicit.

The modifiers public and static are required.

Required

 

Operator

Keyword

Source

 

 

public static implicit operator

TargetType ( SourceType Identifier )

{

 

 

 

 

 

Implicit or explicit

 

 

 

...

return ObjectOfTargetType;

}

For example, the following shows an example of the syntax of a conversion method that converts an object of type Person to an int:

public static implicit operator int(Person p)

{

return p.Age;

}

Constraints on User-Defined Conversions

There are some important constraints on user-defined conversions. The most important are the following:

You can only define user-defined conversions for classes and structs.

You cannot redefine standard implicit or explicit conversions.

The following is true for source type S and target type T:

S and T must be different types.

S and T cannot be related by inheritance. That is, S cannot be derived from T, and T cannot be derived from S.

Neither S nor T can be an interface type or the type object.

The conversion operator must be a member of either S or T.

You cannot declare two conversions, one implicit and the other explicit, with the same source and target types.

458

CHAPTER 18 CONVERSIONS

Example of a User-Defined Conversion

The following code defines a class called Person that contains a person’s name and age. The class also defines two implicit conversions. The first converts a Person object to an int value. The target int value is the age of the person. The second converts an int to a Person object.

class Person

 

 

{

 

 

 

public

string Name;

 

public

int

Age;

 

public

Person(string name, int age)

 

{

 

 

 

Name = name;

 

Age

= age;

 

 

}

 

 

 

public

static implicit operator int(Person p)

// Convert Person to int.

{

 

 

 

return p.Age;

 

}

 

 

 

public

static implicit operator Person(int i)

// Convert int to Person.

{

 

 

 

return new Person("Nemo", i);

}

}

class Program

{

static void Main( )

{

Person bill = new Person( "bill", 25);

Convert a Person object to an int.

int age = bill;

Console.WriteLine("Person Info: {0}, {1}", bill.Name, age);

Convert an int to a Person object.

Person anon = 35;

Console.WriteLine("Person Info: {0}, {1}", anon.Name, anon.Age);

}

}

459

CHAPTER 18 CONVERSIONS

This code produces the following output:

Person Info: bill, 25

Person Info: Nemo, 35

If you had defined the same conversion operators as explicit rather than implicit, then you would have needed to use cast expressions to perform the conversions, as shown here:

Explicit

...

public static explicit operator int( Person p )

{

return p.Age;

}

...

static void Main( )

{

... Requires cast expression

int age = (int) bill;

...

460

CHAPTER 18 CONVERSIONS

Evaluating User-Defined Conversions

The user-defined conversions discussed so far have directly converted the source type to an object of the target type in a single step, as shown in Figure 18-26.

Figure 18-26. Single-step user-defined conversion

But user-defined conversions can have up to three steps in the full conversion. Figure 18-27 illustrates these stages, which include the following:

The preliminary standard conversion

The user-defined conversion

The following standard conversion

There is never more than a single user-defined conversion in the chain.

Figure 18-27. Multistep user-defined conversion

Example of a Multistep User-Defined Conversion

The following code declares class Employee, which is derived from class Person.

Several sections ago, the code sample declared a user-defined conversion from class Person to int. So if there is a standard conversion from Employee to Person and one from int to float, you can convert from Employee to float.

There is a standard conversion from Employee to Person, since Employee is derived from

Person.

There is a standard conversion from int to float, since that is an implicit numeric conversion.

Since all three parts of the chain exist, you can convert from Employee to float. Figure 18-28 illustrates how the compiler performs the conversion.

461

CHAPTER 18 CONVERSIONS

class Employee : Person { }

class Person

 

{

 

public string

Name;

public int

Age;

// Convert a Person object to an int.

public static implicit operator int(Person p)

{

return p.Age;

}

}

class Program

{

static void Main( )

{

Employee bill = new Employee(); bill.Name = "William";

bill.Age = 25;

Convert an Employee to a float.

float fVar = bill;

Console.WriteLine("Person Info: {0}, {1}", bill.Name, fVar);

}

}

This code produces the following output:

Person Info: William, 25

Figure 18-28. Conversion of Employee to float

462

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