АкушерствоАнатомияАнестезиологияВакцинопрофилактикаВалеологияВетеринарияГигиенаЗаболеванияИммунологияКардиологияНеврологияНефрологияОнкологияОториноларингологияОфтальмологияПаразитологияПедиатрияПервая помощьПсихиатрияПульмонологияРеанимацияРевматологияСтоматологияТерапияТоксикологияТравматологияУрологияФармакологияФармацевтикаФизиотерапияФтизиатрияХирургияЭндокринологияЭпидемиология

Type conversions in C#

With the List<T> method ConvertAll<TOutput>(), all types of a collection can be converted to a different type. The ConvertAll<TOutput>() method uses a Converter delegate that is defined like this: public sealed delegate TOutput Converter<TInput, TOutput>(TInput from);

The generic types TInput and TOutput are used with the conversion. TInput is the argument of the delegate method, and TOutput is the return type.

In this example, all Racer types should be converted to Person types. Whereas the Racer type contains a firstName, lastName, country, and the number of wins, the Person type contains just a name. For the conversion, the country of the racer and race wins can be ignored, but the name must be converted:

public class Person

{ private string name;

public Person(string name)

{ this.name = name;

}

public override string ToString()

{ return name;

}

}

 

The conversion happens by invoking the racers.ConvertAll < Person > () method. The argument of this method is defined as a Lambda expression with an argument of type Racer and a Person type that is returned. In the implementation of the Lambda expression, a new Person object is created and returned. For the Person object, the FirstName and LastName are passed to the constructor:

List < Person > persons =

racers. ConvertAll < Person > (

r = > new Person(r.FirstName + " " + r.LastName));

The result of the conversion is a list containing the converted Person objects: persons of type

List < Person >.


Дата добавления: 2015-09-18 | Просмотры: 502 | Нарушение авторских прав



1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |



При использовании материала ссылка на сайт medlec.org обязательна! (0.003 сек.)