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

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

问题描述

受到 Phil Haack尝试null或空白的启发coalescing ,我试图为 string 对象以及 IEnumerable< T> 接口,以简化null或emtpy ckecking。但是,我遇到了问题:当我试图调用 string 版本 AsNullIsEmpty 将我的字符串视为 IEnumerable< char> ,当然会返回错误的返回类型。

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 不是 string ?类似

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.

对于你的具体问题(我可以指定一个反约束一个通用类型参数?),答案是否定的。您可以使用 Obsolete 属性非常接近。

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天全站免登陆