开发者

C# Generics: What is generic constraining interface?

On MSDN - C# Programming guide Constraints on Type Parameters, it says:

开发者_StackOverflow

where T : interface_name

The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

Could somebody kindly explain, what it means to have a generic interface? And explain how that can be a constraint and what it provides?

A simple example and a simple explanation is highly appreciated.

Many thanks in advance : )


You can use a generic interface as a constraint. For example:

class MyClass<T> where T:IEnumerable<string>

you can even substitute the generic parameter of the type you define into your constraint:

class MyClass<T> where T:IEnumerable<T>


An example of a generic interface is IEnumerable<T>. It represents some collection you can enumerate. The type of the items in the collection is not relevant to the interface, so it allows you to specify that with a generic parameter.

You can for example create a class like this:

class Foo<T, E> where T : IEnumerable<E>
{ }

This way, the generic parameter T can only be a collection of type E. The constraining interface is generic as well. You can also do this:

class Foo<T> where T : IEnumerable<string>
{ }

In which case you're not allowing any type of collection, only collections of strings. You can go pretty crazy with this, like this:

class Foo<T> where T : IEnumerable<T>
{ }

Where T has to be some collection that contains collections of T.


One use is when you want a function or class to work generically but want to constrain which types can be used with it (so you don't have to make multiple overloads for instance).

Completely arbitrary code example:

interface IAnimal { }
interface IShape { }

class Tiger : IAnimal { }
class Wolf : IAnimal { }

class Circle : IShape { }
class Rectangle : IShape { }

public void MakeSound<T>(T animal) where T : IAnimal
{
}

public void Draw<T>(T shape) where T : IShape
{
}

This isn't actually how you would structure this type of functionality mind you :) You can use other constraints too:

public void someFunction<T>(T input) where T : IShape, new() // constraint to IShape, allow construction of new T with parameterless constructor

All in all they are useful for generic functions constrained to certain types.


The sentence only states that the constraining interface can not only be a class or interface, but a generic one too.

For instance, such a constraint is a valid one:

public class Controller<TModel,TRepository> where TRepository: Repository<TModel>{...}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜