开发者

.net: How to enforce some limitations on Generics?

Is it possible enforcing som开发者_JAVA技巧e limitations on Type T in Generics?


Yes, you can put some constraints on T. The constraints are introduced with where clause. Check here

where T: struct

The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information.

where T: class

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

where T : new()

The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

where T : <base class name>

The type argument must be or derive from the specified base class.

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.

where T : U

The type argument supplied for T must be or derive from the argument supplied for U.


Basically

public class MyClass<T> where T : ISomeInterface

for example. Lots of existing SO questions too, like this one for extra detail.


Please see generic parameter constraints. When creating your own generic types and methods, constraints allow you to apply some rules concerning the type parameters e.g. that they support required interfaces or have a default constructor.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜