We can add constraints to generic type parameters with the following syntax.
where: constraint
The constraints can be the follows:
Constraint | Meaning |
---|---|
where T : base-class | Base class constraint |
where T : interface | Interface constraint |
where T : class | Reference-type constraint |
where T : struct | Value-type constraint |
where T : new() | Parameterless constructor constraint |
where U : T | Naked type constraint |
using System;
class Shape{
}
class Rectangle: Shape{
}
class Circle: Shape{
}
class GenericClass<T> where T : Shape{
}
class Test
{
static void Main()
{
GenericClass<Rectangle> g = new GenericClass<Rectangle>();
}
}
interface constraint
using System;
interface PrintTable{
void print();
}
class Rectangle : PrintTable
{
}
class GenericClass<T> where T : PrintTable
{
}
class Test
{
static void Main()
{
GenericClass<Rectangle> g = new GenericClass<Rectangle>();
}
}
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |