在C#泛型反约束 [英] Anti-constraint on C# generics

查看:114
本文介绍了在C#泛型反约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

菲尔哈克对空或空凝聚灵感的尝试,我想写一对夫妇的扩展方法为字符串的对象,以及在的IEnumerable< T> 接口,以便简化空或emtpy ckecking。不过,我遇到了问题:当我试图调用字符串 AsNullIsEmpty 的版本,编译器把我的字符串作为的IEnumerable<焦炭方式> ,当然给出了错误的返回类型

Inspired by Phil Haack's attempt on null or empty coalescing, I'm trying to write a couple of extension methods for the string object, as well as on the IEnumerable<T> interface, to simplify null or emtpy ckecking. However, I'm running into problems: when I'm attempting to call the string version of AsNullIsEmpty, the compiler treats my string as an IEnumerable<char>, and of course gives the wrong return type.

有什么办法把反限制关于的IEnumerable 新版本的定义,这样我可以告诉编译器使用一个每当类型 T 是的字符串?类似

Is there any way to put an "anti-constraint" on the definition of the IEnumerable version, so that I can tell the compiler to use that one whenever the type of T is not string? Something like

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



我知道,我可以只改变其中一人的名字,但我想有一致性的同名

I know that I could just change the name of one of them, but I want to have the same name for consistency.

更新:原来我与扩展方法问题解决了另一种方式,通过固定一个简单的和愚蠢的错误(我用的是 str.IsNullOrEmpty(),在扩展方法IEnumerable的< T> 而不是 string.IsNullOrEmpty,(STR) ...),但由于仿制药反制约的问题仍然是一个有趣的,我不会删除。

Update: It turns out my problem with the extension methods was solved another way, by fixing a simple and stupid error (I was using str.IsNullOrEmpty(), the extension method on IEnumerable<T>, instead of string.IsNullOrEmpty(str)...) but since the question of anti-constraints on generics is still an interesting one, I won't delete it.

推荐答案

要做到这一点的唯一方法是创建这个扩展的超载一个接受字符串这个参数。

The only way to do this would be to create an overload of this extension that accepts a string as its this parameter.

public static string AsNullIfEmpty(this string value)

这样做会引起特别类型版本被认为比普通版本更好的过载的匹配。

Doing this will cause the specifically-typed version to be considered a better overload match than the generic version.

关于你提到的具体问题(我可以指定一个'反约束'一个泛型类型参数?),答案是否定的。你可以得到非常接近,虽然与过时属性。

As to your specific question ("Can I specify an 'anti-constraint' on a generic type parameter?"), the answer is no. You could get very close, though, with the Obsolete attribute.

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

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

This would cause the compiler to report an error for this overload.

这篇关于在C#泛型反约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆