何时可以泛型参数不能为空 [英] When can a generic parameter never be null
问题描述
在一个通用的的GetHashCode(T富)
的方法,我检查富
是空
。
但是我只是偶然发现了一个奇怪的ReSharper的警告。
在下面的代码,可以通过富
从不为空
私有类FooComparer< T> :&的IEqualityComparer LT; T>其中T:富
{
公众诠释的GetHashCode(T富)
{
// ReSharper的警告:表情总是假的
如果(Object.ReferenceEquals(空,富))返回0;
// ...计算哈希值
}
}
不过,据我所知道的,下面是完全合法的:
富富= NULL;
变种fooComparer =新FooComparer<富>();
INT哈希= fooComparer.GetHashCode(富);
方法的IEqualityComparer< T> .GetHashCode
有合约 [NOTNULL]
为它的参数,因为它有抛出一个异常实现时空$ C 。$ C>是作为一个参数
如果你想使用 FooComparer< T> .GetHashCode
直接异常安全的空
作为它的参数,可以按以下方式将其标注为:
公众诠释的GetHashCode([JetBrains.Annotations.CanBeNull] T,富)
{
// ReSharper的警告:表情总是假的
如果(Object.ReferenceEquals(NULL,富))返回0;
// ...计算哈希值
}
不过分析 [非空]
α参数必须提高。这个bug存在类似的代码在 http://youtrack.jetbrains.com/issue/RSRP-304111
In a generic GetHashCode(T foo)
method, I check whether foo
is null
.
However I just stumbled upon a strange Resharper warning.
In the following code, can foo
never be null
?
private class FooComparer<T> : IEqualityComparer<T> where T: Foo
{
public int GetHashCode(T foo)
{
// resharper warning: "Expression is always false"
if (Object.ReferenceEquals(null,foo)) return 0;
// ... calculate hash
}
}
However as far as I can tell, the following is perfectly legal:
Foo foo = null;
var fooComparer = new FooComparer<Foo>();
int hash = fooComparer.GetHashCode(foo);
Method IEqualityComparer<T>.GetHashCode
has contract [NotNull]
for its parameter because it has implementations that throw an exception when null
is provided as an argument.
If you want to use FooComparer<T>.GetHashCode
directly and exception-safe for null
as its argument, you can annotate it as follows:
public int GetHashCode([JetBrains.Annotations.CanBeNull] T foo)
{
// resharper warning: "Expression is always false"
if (Object.ReferenceEquals(null,foo)) return 0;
// ... calculate hash
}
Nevertheless analysis for [Not-Null]
-parameters must be improved. This bug exists for similar code in http://youtrack.jetbrains.com/issue/RSRP-304111
这篇关于何时可以泛型参数不能为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!