c# - 通过特定的 where 子句在 C# 中创建通用方法

标签 c# .net generics generic-collections generic-constraints

我想创建一些通用方法,如下面的代码:

public async Task<T> Get<T>(string url) where T : IBaseModel, IList<IBaseModel>

显然我想支持可枚举集合以及从IBaseModel接口(interface)驱动的单个对象。 方法定义没问题,但是当涉及到它的使用时,我会收到以下错误:

await myClass.Get<List<DrivedClassFromBaseModel>>("some url");

There is no implicit conversion from "System.Collection.Generic.List<DrivedClassFromBaseModel> to System.Collection.Generic.IList<IBaseModel>"

最佳答案

Generic constraints将通过 AND 组合,因此 where T : IBaseModel, IList<IBaseModel>意味着 T应该同时实现 IBaseModelIList<IBaseModel> .

您需要创建两个方法:

public async Task<T> Get<T>(string url) where T : IBaseModel
public async Task<IList<T>> GetList<T>(string url) where T : IBaseModel

关于c# - 通过特定的 where 子句在 C# 中创建通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53977528/

相关文章:

c# 最安全的方法检查一个类型是否在其接口(interface)中包含一个类型

c# - 字典的 IEnumerator 是否保证一致?

.net - ReportViewer 控件加载指示器?

c# - Moq 使用 ReturnsAsync 并修改 It.IsAny 输入参数

c# - WPF - ListView 更新非常零星

c# - 错误 : 'Operand type clash: date is incompatible with int ' on date type

c# - EF TPT 生成重复的外键

c++ - 如何从 C++ 中的函数返回一个 vector<T>

java - 如何避免为泛型类型创建特定实现

java - 什么是原始类型,为什么我们不应该使用它?