c# - C#泛型的反约束

标签 c# generics constraints

灵感来自 Phil Haack's attempt on null or empty coalescing ,我正在尝试为 string 编写几个扩展方法对象,以及 IEnumerable<T>接口(interface),以简化 null 或 emtpy ckecking。但是,我遇到了问题:当我试图调用 string AsNullIsEmpty 的版本,编译器将我的字符串视为 IEnumerable<char> ,当然会给出错误的返回类型。

有没有办法在 IEnumerable 的定义上加上“反约束”?版本,这样我就可以告诉编译器在 T 的类型时使用那个版本不是 string ?有点像

public static IEnumerable<T> AsNullIfEmpty(this IEnumerable<T> items)
    where T !: string

我知道我可以更改其中一个的名称,但为了保持一致性,我想使用相同的名称。

更新:事实证明,我的扩展方法问题已通过另一种方式解决,方法是修复一个简单而愚蠢的错误(我使用的是 str.IsNullOrEmpty()IEnumerable<T> 上的扩展方法,而不是string.IsNullOrEmpty(str) ...) 但由于泛型的反约束问题仍然是一个有趣的问题,我不会删除它。

最佳答案

实现此目的的唯一方法是创建此扩展的重载,它接受 string 作为其 this 参数。

public static string AsNullIfEmpty(this string value)

这样做会导致特定类型的版本被认为是比通用版本更好的重载匹配。

至于您的具体问题(“我可以在泛型类型参数上指定‘反约束’吗?”),答案是否定的。不过,您可以使用 Obsolete 属性非常接近。

[Obsolete("AsNullIfEmpty is not supported for strings.", true)]
public static string AsNullIfEmpty(this string value)

这会导致编译器报告此重载错误。

关于c# - C#泛型的反约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3255450/

相关文章:

c# - 自动映射器的通用扩展方法

c# - 我在实现通用存储库时遇到问题

Java Generics Puzzler,扩展类并使用通配符

ios - Swift 表格 View 单元格比例高度

hash - 如何防止这个循环多项式哈希函数使用类型约束?

c# - 实体类型 ApplicationUser 不是当前上下文 Asp.Net MVC 模型的一部分

c# - 使用 ExeCOMServer 时无法将类型为 '...' 的 COM 对象转换为接口(interface)类型 '...'

grails - Grails GORM约束

c# - 提供程序 'SqlServer-20' 没有元数据信息

c# - SHA256哈希计算