首页 > 解决方案 > 如何实现接受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

标签: c#nullability

解决方案


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?

推荐阅读