继承一个通用基类,应用约束,并在C#中实现一个接口, [英] Inherit from a generic base class, apply a constraint, and implement an interface in C#

查看:631
本文介绍了继承一个通用基类,应用约束,并在C#中实现一个接口,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个语法问题。我有一个通用类继承一个通用基类,并且正在对一个类型参数应用约束。我还希望派生类实现一个接口。对我的生活,我似乎无法找出正确的语法。

This is a syntax question. I have a generic class which is inheriting from a generic base class and is applying a constraint to one of the type parameters. I also want the derived class to implement an interface. For the life of me, I cannot seem to figure out the correct syntax.

这是我有:

DerivedFoo<T1,T2> : ParentFoo<T1, T2> where T2 : IBar { ... }

第一件事是: p>

The first thing that came to mind was this:

DerivedFoo<T1,T2> : ParentFoo<T1, T2> where T2 : IBar, IFoo { ... }

但是这是不正确的,因为T2会需要实现IBar和IFoo,而不是DerivedFoo来实现IFoo。

But that is incorrect as that causes T2 to need to implement both IBar and IFoo, not DerivedFoo to implement IFoo.

我尝试过一些Googling,使用冒号,分号等,短路。

I've tried a bit of Googling, use of colons, semicolons, etc, but I've turned up short. I'm sure the answer is head slappingly simple.

推荐答案

在定义通用约束之前,您需要包括类的整个签名。

You include the entire signature of your class before you define generic constraints.

class DerivedFoo<T1, T2> : ParentFoo<T1, T2>, IFoo where T2 : IBar
{
    ...
}

这篇关于继承一个通用基类,应用约束,并在C#中实现一个接口,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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