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

Tuples in C#

Arrays combine objects of the same type; tuples can combine objects of different types. Tuples have the origin in functional programming languages such as F# where they are used often. With.NET 4, tuples are available with the.NET Framework for all.NET languages.

.NET 4 defines eight generic Tuple classes and one static Tuple class that act as a factory of tuples. The different generic Tuple classes are here for supporting a different number of elements; e.g., Tuple<T1> contains one element, Tuple<T1, T2> contains two elements, and so on.

The method Divide() demonstrates returning a tuple with two members — Tuple<int, int>. The parameters of the generic class define the types of the members, which are both integers. The tuple is created with the static Create() method of the static Tuple class. Again, the generic parameters of the Create() method define the type of tuple that is instantiated. The newly created tuple is initialized with the result and reminder variables to return the result of the division:

public static Tuple<int, int> Divide(int dividend, int divisor)

{

int result = dividend / divisor;

int reminder = dividend % divisor;

return Tuple.Create<int, int>(result, reminder);

}

The following code shows invoking the Divide() method. The items of the tuple can be accessed with the

properties Item1 and Item2:

var result = Divide(5, 2);

Console.WriteLine("result of division: {0}, reminder: {1}",

result.Item1, result.Item2);

The last template parameter is named TRest to indicate that you must pass a tuple itself. That way you can create tuples with any number of parameters.

To demonstrate this functionality: public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> Here, the last template parameter is a tuple type itself, so you can create a tuple with any number of items:

var tuple = Tuple.Create<string, string, string, int, int, int, double,

Tuple<int, int>>("Stephanie", "Alina", "Nagel", 2009, 6, 2, 1.37,

Tuple.Create<int, int>(52, 3490));


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



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.004 сек.)