The where clause is used to specify constraints on the types that can be acclimated as arguments for a blazon parameter defined in a generic declaration. For example, you can declare a generic class such that the type parameter T implements the IComparable<T> interface:
// cs_where.cs
// compile with: /target:library
using System;
class MyClassy<T, U>
where T : class
where U : struct
{
}
The new() Constraint lets the compiler know that any type argument supplied must have an accessible parameterless--or default-- constructor.
For example:
// cs_where_2.cs
// compile with: /target:library
using System;
public class MyGenericClass <T> where T: IComparable, new()
{
// The following line is not possible without new() constraint:
T item = new T();
}
With multiple type parameters, use one where clause for each type parameter
For example:
// cs_where_3.cs
// compile with: /target:library
using System;
using System.Collections;
interface MyI
{
}
class Dictionary<TKey,TVal>
where TKey: IComparable, IEnumerable
where TVal: MyI
{
public void Add(TKey key, TVal val)
{
}
}
0 comments:
Post a Comment