четверг, 22 апреля 2010 г.

Generic Constraint Meaning in Life

Generic Constraint Meaning in Life
where T : struct Тип параметра должен быть System.ValueType в цепочке наследования.

where T : class The type parameter must not have System.ValueType in its chain of inheritance (e.g., must be a reference type).

where T : new() default constructor.
This is The type parameter must have a very helpful if your generic type must create an instance of the type parameter,
as you cannot assume the format of custom constructors. Note that this constraint must be listed last on a multiconstrained type.

where T : NameOfBaseClass derived from the class specified The type parameter must be by NameOfBaseClass.

where T : NameOfInterface The type parameter must implement the interface specified by NameOfInterface.
Multiple interfaces can be separated as a comma-delimited list.
When constraints are applied using the where keyword, the constraint list is placed after the generic type’s base class and interface list.
By way of a few concrete examples, consider the following constraints of a generic class named MyGenericClass:
/ MyGenericClass derives from Object, while
// contained items must have a default ctor.

public class MyGenericClass where T : new()
{...}

// MyGenericClass derives from Object, while
// contained items must be a class implementing IDrawable
// and support a default ctor.

public class MyGenericClass where T : class, IDrawable, new()
{...}

// MyGenericClass derives from MyBase and implements ISomeInterface,
// while the contained items must be structures.

public class MyGenericClass : MyBase, ISomeInterface where T : struct
{...}

On a related note, if you are building a generic type that specifies multiple type parameters,
you can specify a unique set of constraints for each:

// must have a default ctor, while must
// implement the generic IComparable interface.

public class MyGenericClass where K : new() where T : IComparable
{...}

Комментариев нет: