带有“任何泛型类型”定义的 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:38:50  来源:igfitidea点击:

C# generic "where constraint" with "any generic type" definition?

c#genericswheretype-constraints

提问by Nenad

Let me give example:

我举个例子:

  1. I have some generic class/interface definition:

    interface IGenericCar< T > {...}

  2. I have another class/interface that I want to relate with class above, for example:

    interface IGarrage< TCar > : where TCar: IGenericCar< (**any type here**) > {...}

  1. 我有一些通用的类/接口定义:

    interface IGenericCar< T > {...}

  2. 我有另一个类/接口,我想与上面的类相关联,例如:

    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 IGarragerepresenting the Twhich 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 > {...}