指定generics类,其中T应该是其他类型的子类
这是我想要做的,甚至不确定是否可能..
我正在创建BaseViewModel
,我希望它接受从Entity
inheritance的类型
考虑以下代码:
public abstract class BaseViewModel : NotificationObject, INavigationAware { public T MyEntity; public SomeMethod() { MyEntity.SomeEntityProperty = SomeValue; } }
所以,我想说我的T
inheritance自Entity
,因此我知道它会有SomeEntityProperty。
这可能吗?
Salvatore的回答是完全正确的,我只想更好地描述这个概念。
你需要的是一个“通用类型约束”; 指定用作T的类型必须符合某些行为(例如从比Object更多派生的对象或接口派生),从而增加您对该对象的允许操作而无需进一步转换(通常应避免)在generics)。
正如Salvatore的回答所示,GTC使用“where”关键字定义:
public abstract class BaseViewModel : NotificationObject, INavigationAware where T : Entity; { ...
该GTC基本上声明任何T必须从实体派生(但是远程)。 这允许您将T视为实体(除了实例化新Ts;需要额外的GTC),无论实际通用参数类型或多或少地来自实体。 您可以调用实体上显示的任何方法,并获取/设置任何字段或属性。
您还可以指定:
public abstract class BaseViewModel : NotificationObject, INavigationAware where T : Entity { public T MyEntity; public SomeMethod() { MyEntity.SomeEntityProperty = SomeValue; } }
只需使用where
关键字:
public abstract class BaseViewModel : NotificationObject, INavigationAware where T:Entity { ...
尝试使用where约束:
上述就是C#学习教程:指定generics类,其中T应该是其他类型的子类分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public abstract class BaseViewModel : NotificationObject, INavigationAware where T : Entity { public T MyEntity; public SomeMethod() { MyEntity.SomeEntityProperty = SomeValue; } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/991908.html