如何在C#7.3中编写保留原集合类型的.NullIfEmpty()扩展方法?
实现保留原始类型的NullIfEmpty扩展方法
你遇到的核心问题是既要让扩展方法返回原始集合类型,又要保证类型推断正常工作,其实修正代码中的笔误后,你的第三种写法是可行的。
正确的实现代码
public static class CollectionExtensions { public static C NullIfEmpty<C, E>(this C collection) where C : IReadOnlyCollection<E> { return collection.Count == 0 ? null : collection; } }
为什么这个写法能工作?
在C# 7.3中,编译器可以从集合类型C的已实现接口推断出元素类型E。例如:
- 当你传入
List<string>时,编译器会识别到它实现了IReadOnlyCollection<string>,自动推断C = List<string>、E = string,返回类型也会是List<string>,不会丢失原始类型。
调用示例
// 空集合返回null List<string> emptyList = new List<string>(); List<string> result1 = emptyList.NullIfEmpty(); // result1为null // 非空集合返回自身 List<string> nonEmptyList = new List<string> { "test" }; List<string> result2 = nonEmptyList.NullIfEmpty(); // result2指向原nonEmptyList
特殊情况处理
如果遇到某些自定义集合类型导致类型推断失效(极少发生),可以显式指定泛型参数:
MyCustomCollection<int> customCollection = new MyCustomCollection<int>(); var result = customCollection.NullIfEmpty<MyCustomCollection<int>, int>();
内容的提问来源于stack exchange,提问作者Marcel
相关产品推荐
相关产品推荐

