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

When creating generic classes, you might need some more C# keywords

Прочитайте:
  1. Creating generic classes in C#.
  2. Generics in C#.
  3. Not required to assign the generic type with the method call. The generic method can be invoked as simply

a. Default values: - It is not possible to assign null to generic type

- We can use default keyword to initialize default(either 0 or null) value

b. Constraints – If Generic class needs to invoke some methods from the generic type we have to add constraints.

where T: struct With a struct constraint, type T must be a value type.

where T: class Class constraint indicates that type T must be a reference type.

where T: IFoo where T: IFoo specifies that type T is required to implement interface IFoo.

where T: Foo where T: Foo specifi es that type T is required to derive from base class Foo.

where T: new() where T: new() is a constructor constraint and specifies that type T must have a default constructor.

where T1: T2 With constraints it is also possible to specify that type T1 derives from a generic

type T2. This constraint is known as naked type constraint.

c. Inheritance: - A generic type can implement a generic interface.

- When deriving from generic base class, you must provide a type argument instead of the base-class’s generic type parameter.

public class LinkedList<T>: IEnumerable<T>

{//...

A generic type can implement a generic interface. The same is possible by deriving from a class. A generic class can be derived from a generic base class:

public class Base<T> { }

public class Derived<T>: Base<T> { }

the derived class can be a generic or non-generic class. For example, you can define an abstract generic base class that is implemented with a concrete type in the derived class. This allows you to do specialization for specific types:

public abstract class Calc<T>

{

public abstract T Add(T x, T y);

public abstract T Sub(T x, T y);

}

public class IntCalc: Calc<int>

{

public override int Add(int x, int y)

{

return x + y;

}

public override int Sub(int x, int y)

{

return x — y;

}

}

d. Static Members – static members of generic class are only shared with one instatiation of the class.

 


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



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