What does the keyword “where” in a class declarati

2020-02-10 17:34发布

I'm looking at the source code for the MvcContrib Grid and see the class declared as:

public class Grid<T> : IGrid<T> where T : class

What does the where T : class bit do?

标签: c#
7条回答
一夜七次
2楼-- · 2020-02-10 17:57

It's a generic type constraint. It specifies that the type T has to be a reference type, i.e. a class and not a structure.

查看更多
\"骚年 ilove
3楼-- · 2020-02-10 17:59

It is a generic type constraint.

In this case it means that the generic type (T) must be a reference type, that is class, interface, delegate, or array type.

Other constraints are listed here.

You can also constrain the generic type to inherit from a specific type (base class or interface)

查看更多
我命由我不由天
5楼-- · 2020-02-10 18:06

you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class are called as Constraints on Type Parameters

E.g : where T : class

Here where T is the Type , The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

查看更多
干净又极端
6楼-- · 2020-02-10 18:08

It is a constraint on the type argument which says that T can either be a class or an interface but not an enum or a struct. So T must be a reference type and not a value type.

Best Regards,
Oliver Hanappi

查看更多
Animai°情兽
7楼-- · 2020-02-10 18:09

From the Docs http://msdn.microsoft.com/en-us/library/d5x73970.aspx

where T : class

The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

查看更多
登录 后发表回答