带有“任何泛型类型”定义的 C# 泛型“where 约束”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1541152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# generic "where constraint" with "any generic type" definition?
提问by Nenad
Let me give example:
我举个例子:
I have some generic class/interface definition:
interface IGenericCar< T > {...}
I have another class/interface that I want to relate with class above, for example:
interface IGarrage< TCar > : where TCar: IGenericCar< (**any type here**) > {...}
我有一些通用的类/接口定义:
interface IGenericCar< T > {...}
我有另一个类/接口,我想与上面的类相关联,例如:
interface IGarrage< TCar > : where TCar: IGenericCar< (**any type here**) > {...}
Basically, I want my generic IGarrage to be dependent on IGenericCar
, regardless if it's IGenericCar<int>
or IGenericCar<System.Color>
, because I don't have any dependency to that type.
基本上,我希望我的通用 IGarrage 依赖于IGenericCar
,无论它是IGenericCar<int>
或IGenericCar<System.Color>
,因为我对该类型没有任何依赖性。
采纳答案by JaredPar
There are typically 2 ways to achieve this.
通常有两种方法可以实现这一点。
Option1: Add another parameter to IGarrage
representing the T
which should be passed into the IGenericCar<T>
constraint:
Option1:添加另一个参数来IGarrage
表示T
应该传递给IGenericCar<T>
约束的参数:
interface IGarrage<TCar,TOther> where TCar : IGenericCar<TOther> { ... }
Option2: Define a base interface for IGenericCar<T>
which is not generic and constrain against that interface
选项2:定义一个IGenericCar<T>
非通用的基本接口并限制该接口
interface IGenericCar { ... }
interface IGenericCar<T> : IGenericCar { ... }
interface IGarrage<TCar> where TCar : IGenericCar { ... }
回答by snarf
Would it make any sense to do something like:
这样做是否有意义:
interface IGenericCar< T > {...}
interface IGarrage< TCar, TCarType >
where TCar: IGenericCar< TCarType > {...}