简体   繁体   English

C#泛型:如何应用泛型类型约束并从基类型继承

[英]C# Generics: How to apply a generic type constraint AND inherit from basetype

This is what I am trying to do: 这就是我想要做的:

DataService<T> where T : SomeType : DataServiceBase

In other words, I want to introduce a T where it is a subclass of Sometype. 换句话说,我想介绍一个T,它是Sometype的子类。 But I also need DataService to inherit from DataServiceBase. 但是我还需要DataService从DataServiceBase继承。

It seems I can do one or the other, but not both because there are two colons used. 看来我可以做一个或另一个,但不能两者都做,因为有两个冒号被使用。 In other words, I can use the generic selector of " where : SomeType" or if I don't use that, I can inherit from DataServiceBase. 换句话说,我可以使用“ where:SomeType”的通用选择器,或者如果不使用它,则可以从DataServiceBase继承。 But if I do both, it generates a design time error. 但是,如果我同时执行,则会生成设计时错误。

OK, got it to work like this: 好,让它像这样工作:

DataService<T> : DataServiceBase where T : SomeType

Greg 格雷格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM