Взято из книжки по подготовке экзамена microsoft "MCTS Self-Paced Training Kit (Экзамен 70-536)", Глава 1 (Framework fundamentals), Урок 3 (What are generics).
How to Use Constraints
Generics would be extremely limited if you could only write code that would compile for any class, because you would be limited to the capabilities of the base Object class.To overcome this limitation, use constraints to place requirements on the types thatconsuming code can substitute for your generic.
Generics support four types of constraints:
- Interface Allow only types that implement specific interfaces to use your generic.
- Base class Allow only types that match or inherit from a specific base class to use your generic.
- Constructor Require types that use your generic to implement a parameterless constructor.
- Reference or value type Require types that use your generic to be either a reference or value type.
Use the As clause in Visual Basic or the where clause in C# to apply a constraint to a generic.
Разберемся - для generic мы можем выставлять ограничение с помощью ключевого слова where, типа как далее:
class Abc<T> where T : IDisposable
{ ... }
Ну это понятно, теперь разберемся с самими ограничениями, с первыми двумя - все и так понятно, а вот на последние два авторы как-то забыли объяснить и дать пример.
1. parameterless constructor - требование безпараметрического конструктора. По-суть очень полезно, если внутри своего класса вы хотите создавать новые экземпляры обобщенного класса. Все очень просто, нужно написать new(). Кстати без данного ограничения вы не сможете написать T it = new T()... :)
class Abc<T> where T : new()
{
public void DoSmth()
{
T it = new T();
}
}
2. Reference or value type. Тоже может быть очень полезным - так как мы можем полностью отсечь применения типа Abc<int> и т.д. Тут сложнее: для referenced type должно идти ключевое слово class, для value type - ключевое слово struct.
class Abc<T> where T : class
{ ... }
class Cba<T> where T : struct
{ ... }
Честно говоря, когда я узнал что так можно делать - у меня был шок. Сразу же разрешилось несколько проблем в проектах :) Надеюсь кому-нибудь это тоже пригодится.