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

Generics in C#

With generics, you can create classes and methods that are independent of

contained types. Instead of writing a number of methods or classes with the same functionality for different types, you can create just one method or class. Generics introduce to the.NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. Generic types are used to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes.

Example: / / Declare the generic class.

public class GenericList<T>

{void Add(T input) { }

}

class TestGenericList

{ private class ExampleClass { }

static void Main()

{// Declare a list of type int.

GenericList<int> list1 = new GenericList<int>();

// Declare a list of type string.

GenericList<string> list2 = new GenericList<string>();

// Declare a list of type ExampleClass.

GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();

}

}

Performance: Boxing and unboxing are easy to use but have a big performance impact.Generic allows you to define the type when it is used. In the example here, the generic type of the List < T >class is defined as int, so the int type is used inside the class that is generated dynamically from the JIT compiler. Boxing and unboxing no longer happens

Type Safety: With the generic class List<T>, the generic type T defines what types are allowed. With a definition of List<int>, only integer types can be added to the collection.

Дополнительно var list = new List<int>();

list.Add(44);

list.Add("mystring"); // compile time error

list.Add(new MyClass()); // compile time error

Binary code reuse: Generics allow better binary code reuse. A generic class can be defined once and can be instantiated with many different types.

Code Bloat: when the generic classes are compiled by the JIT

compiler to native code, a new class for every specific value type is created. Reference types share all the same implementation of the same native class.

 


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



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