C# 泛型“where 约束"带有“任何泛型类型"定义? [英] C# generic "where constraint" with "any generic type" definition?

查看:32
本文介绍了C# 泛型“where 约束"带有“任何泛型类型"定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举个例子:

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

  1. I have some generic class/interface definition:

interface IGenericCar<>{...}

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

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

接口IGarrage<车>: 其中 TCar: IGenericCar<(**这里是任何类型**) >{...}

基本上,我希望我的通用 IGarrage 依赖于 IGenericCar,无论它是 IGenericCar 还是 IGenericCar,因为我对该类型没有任何依赖.

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.

推荐答案

通常有两种方法可以实现这一点.

There are typically 2 ways to achieve this.

Option1:向 IGarrage 添加另一个参数,表示应该传递到 IGenericCarT> 约束:

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

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

Option2:为 IGenericCar 定义一个基本接口,该接口不是通用的并且限制该接口

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 { ... }

这篇关于C# 泛型“where 约束"带有“任何泛型类型"定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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