c# - 如何实现接受ICollection的方法和 ICollection
问题描述
给定以下方法:
public static void DisposeItems<T>(this ICollection<T?> collection)
where T : class, IDisposable
{
foreach (var item in collection)
{
item?.Dispose();
}
if (!collection.IsReadOnly)
{
collection.Clear();
}
}
这被称为:
private static void CleanupNullable(List<TestClass?> collection)
{
collection.DisposeItems();
}
private static void Cleanup(List<TestClass> collection)
{
collection.DisposeItems();
}
第二个给出错误: 由于引用类型中的可空性差异,不能使用集合。
类似的实现接受IEnumerable<T?>
工作正常,因为IEnumerable
是协变的。
我无法创建额外的方法接受ICollection<T>
,因为可空性不是签名的一部分。有什么方法可以编译它,因为它可以在可空性之前工作?
删除class
约束或将其更改class?
为在调用时会出错,Collection<TestClass?>
因为TestClass?
与约束不匹配IDisposable
。
解决方案
This is because you've put the question mark in the wrong place. If your generic constraint doesn't care if a type is nullable, you add the question mark to the type in the where expression, rather than the argument list. Plus you need to add that "don't care" question mark to all of the constraints for that type.
public static void DisposeItems<T>(this ICollection<T> collection)
where T : class?, IDisposable?
推荐阅读
- php - Craft CMS element-api 如何在条目中获取类别字段的值
- amazon-web-services - 有没有办法设置一个带有 lambda 函数的计时器,我可以从我的前端开始和停止?
- reactjs - 将 api/json 数据从一个组件传递到 ReactJs 上的另一个组件
- python - 我想读取具有多个名称的字符串并将它们与列表 Python 中的名称匹配
- c# - 实体框架 - 在不总是匹配时进行连接
- javascript - 调用materialize css modal tru php edit
- kubernetes - 如何配置本地 kubectl 远程访问集群?
- javascript - 带有凭据和 Client_ID 的 JavaScript Fetch api (Cornerstone API)
- r - 循环回归永久实体,保存所有实体的预测值
- angular - 如何在使用 Angular 的 Electron 应用程序中使用代码覆盖率?