且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#泛型"其中约束"与"任何泛型类型"定义?

更新时间:2021-08-16 23:36:29

有通常为2的方式来实现这一目标。

There are typically 2 ways to achieve this

选项1:添加另一个参数IGarrage重新presnting应该被传递到T的 IGenericCar< T> 限制

Option1: Add another parameter to IGarrage represnting the T which should be passed into the IGenericCar<T> constraint

interface IGarrage<TCar,TOther> where TCar : IGenericCar<TOther> { ... }

选项2:定义一个基本接口 IGenericCar&LT; T&GT; 这是不通用的,限制针对该接口

Option2: Define a base interface for IGenericCar<T> which is not generic and constrain against that interface

interface IGenericCar { ... }
interface IGenericCar<T> : IGenericCar { ... }
interface IGarrage<TCar> where TCar : IGenericCar { ... }