何时可以泛型参数不能为空 [英] When can a generic parameter never be null

查看:508
本文介绍了何时可以泛型参数不能为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个通用的的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] 为它的参数,因为它有抛出一个异常实现时是作为一个参数



如果你想使用 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屋!

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