C#泛型"其中约束"与"任何泛型类型"定义? [英] C# generic "where constraint" with "any generic type" definition?

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

问题描述

我举的例子:


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

  1. I have some generic class/interface definition:

接口IGenericCar< T> {...}

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

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

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

基本上,我希望我的通用IGarrage依赖于 IGenericCar ,如果不管它是 IGenericCar< INT> IGenericCar< System.Color方式> ,因为我没有任何依赖于该类型

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.

推荐答案

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

There are typically 2 ways to achieve this

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

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

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

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