Dan*_*gby 102 c# generics inheritance interface constraints
这是一个语法问题.我有一个泛型类,它继承自泛型基类,并将约束应用于其中一个类型参数.我还希望派生类实现一个接口.对于我的生活,我似乎无法弄清楚正确的语法.
这就是我所拥有的:
DerivedFoo<T1,T2> : ParentFoo<T1, T2> where T2 : IBar { ... }
Run Code Online (Sandbox Code Playgroud)
首先想到的是:
DerivedFoo<T1,T2> : ParentFoo<T1, T2> where T2 : IBar, IFoo { ... }
Run Code Online (Sandbox Code Playgroud)
但这是不正确的,因为这导致T2需要实现IBar和IFoo,而不是DerivedFoo来实现IFoo.
我尝试了一些谷歌搜索,使用冒号,分号等,但我已经调整了.我确定答案很简单.
Ada*_*son 154
在定义泛型约束之前,请包括类的完整签名.
class DerivedFoo<T1, T2> : ParentFoo<T1, T2>, IFoo where T2 : IBar
{
...
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ert 16
我的建议:当你对C#语言的语法有疑问时,请阅读规范; 这就是我们发布它的原因.您需要阅读第10.1节.
要回答您的具体问题,类声明中的事物顺序是:
除了"class",名称和正文之外,该列表上的所有内容都是可选的,但如果出现,则所有内容都必须按顺序显示.
public interface IFoo {}
public interface IBar {}
public class ParentFoo<T,T1> { }
public class DerivedFoo<T, T1> : ParentFoo<T, T1>, IFoo where T1 : IBar { }
Run Code Online (Sandbox Code Playgroud)