C# 泛型“where 约束"带有“任何泛型类型"定义?

编程入门 行业动态 更新时间:2024-10-04 23:20:46
本文介绍了C# 泛型“where 约束"带有“任何泛型类型"定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

举个例子:

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

  • 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 添加另一个参数,表示应该传递到 IGenericCar 的 T> 约束:

    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 约束"带有“任何泛型类型"定义?

    本文发布于:2023-11-26 23:23:44,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1635631.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:定义   类型   泛型   quot

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!