救世的回答完全正确,我只是想描述这个概念。
你们需要的是“基因类型的限制”;具体地说,作为T的类型必须符合某些行为(例如从物体或比物体更衍生的界面衍生出来的),从而增加允许你在不进一步投放的情况下与该物体做些什么(一般在一般情况下可以避免)。
As Salvatore s answer shows, GTCs are defined using the "where" keyword:
public abstract class BaseViewModel<T> :
NotificationObject,
INavigationAware
where T : Entity;
{
...
地球资源中心基本称,任何T必须(无论远处)从实体获得。 这使你能够将T视作一个实体(除新Ts的即时情况外;这要求增加一个TC,而不论实际通用参数类型如何来自实体。 你可以指实体上出现的任何方法,获取/确定任何领域或财产。
您还可以指出:
- The type must be a class (
where T:class
), or alternately must be a ValueType (where T:struct
). This either permits or prevents comparison and assignment of a T instance to null, which also allows or prevents use of the null-coalescing operator ??
.
- The type must have a parameterless constructor (
where T:new()
). This allows instantiations of Ts using the new
keyword, by ensuring at compile-time that all types used as Ts have a constructor that takes no parameters.