指定泛型类,其中T应该是其它类型的子类 [英] Specify generics class where T should be subclass of other type

查看:813
本文介绍了指定泛型类,其中T应该是其它类型的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面就是我想要做什么,甚至不知道,如果可能的。

Here is what I'm trying to do, not even sure if possible..

我创建 BaseViewModel< T> ,我希望它接受来自实体继承类型

I'm creating BaseViewModel<T> and I want it to accept types inherited from Entity

考虑以下代码:

public abstract class BaseViewModel<T> : NotificationObject, INavigationAware
{

public T MyEntity;

public SomeMethod()
{
MyEntity.SomeEntityProperty = SomeValue;
}

}



所以,我想说的是,我的 T 继承实体,所以我知道这将有SomeEntityProperty。

So, I want to say that my T inherited from Entity and therefore I KNOW that it will have SomeEntityProperty.

这可能吗?

推荐答案

萨尔瓦多的答案是完全正确的,我只是想描述概念好一点

Salvatore's answer is totally correct, I just wanted to describe the concept a little better.

您需要的是一个泛型类型约束。指定用作T中的类型必须符合一定的行为(如从对象或接口比对象更衍生衍生而来),从而增加了你被允许与该对象做什么而无需进一步浇铸(这是通常被避免在仿制药)

What you need is a "generic type constraint"; to specify that the type used as T must conform to certain behaviors (such as being derived from an object or interface more derived than Object), thus increasing what you are allowed to do with that object without further casting (which is generally to be avoided in generics).

由于萨尔瓦托雷的回答表明,贸易总公司使用的是在哪里关键字定义的:

As Salvatore's answer shows, GTCs are defined using the "where" keyword:

public abstract class BaseViewModel<T> :
    NotificationObject,
    INavigationAware

    where T : Entity;
{
   ...

这基本上GTC规定,任何T必须派生(但是远程)从实体。这可以让你把T作为好像它是一个实体(除新的TS的实例;需要额外的GTC),不论如何或多或少产生的实际泛型参数类型与实体。你可以调用实体上出现的任何方法,并获取/设置任何字段或属性。

This GTC basically states that any T must derive (however remotely) from Entity. This allows you to treat T as if it were an Entity (except for instantiation of new Ts; that requires an additional GTC), regardless of how more or less derived the actual generic parameter type is from Entity. You can call any method that appears on Entity, and get/set any field or property.

您也可以指定:


  • 的类型必须是一个类(其中T:类),或交替必须是值类型(其中T:结构)。这允许或阻止一件T实例为null,它也允许或禁止使用空合并运算符 ??
  • $ B $的比较和赋值b
  • 的类型必须有一个特定签名的构造函数(其中T:新的()其中T:新的(整型,浮点) )。这允许使用关键字,TS的实例,确保在编译时所用的TS各类与预期的签名的构造函数。

  • 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 constructor of a particular signature (where T:new(), where T:new(int,float)). This allows instantiations of Ts using the new keyword, by ensuring at compile-time that all types used as Ts have a constructor with the expected signature.

这篇关于指定泛型类,其中T应该是其它类型的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆