简体   繁体   English

使用现有 API 时如何避免可空性警告

[英]How to avoid nullability warning when using existing APIs

I get the following compiler warning when implementing the frameworks IComparer interface.在实现框架 IComparer 接口时,我收到以下编译器警告。 I understand the reason why, but in my case I ensure that I initialize all values of the collection with an instance.我明白原因,但在我的例子中,我确保我用一个实例初始化集合的所有值。 How can I avoid the warning?我怎样才能避免警告? I tried the bang operator but it doesn't seem to be allowed here.我尝试了 bang 运算符,但这里似乎不允许。 Maybe there is an alternative for collections which are known to have no null elements?也许已知没有空元素的集合有替代方案?

warning CS8767: Nullability of reference types in type of parameter 'x' of 'int FooComparer.Compare(Foo x, Foo y)' doesn't match implicitly implemented member 'int IComparer.Compare(Foo? x, Foo? y)' (possibly because of nullability attributes).警告 CS8767:“int FooComparer.Compare(Foo x, Foo y)”的参数“x”类型中引用类型的可空性与隐式实现的成员“int IComparer.Compare(Foo?x, Foo?y)”不匹配(可能是因为可空性属性)。

class FooComparer : IComparer<Foo>
{
    public int Compare(Foo x, Foo y)
    {
        return y.Bar() - x.Bar();
    }
}

Ok I got it solved.好的,我解决了。 Need to declare the arguments as nullable as the contract needs, but in implementation have to use bang to tell what we expect:需要根据合约需要将参数声明为可空,但在实现中必须使用 bang 来告诉我们期望什么:

class FooComparer : IComparer<Foo>
{
    public int Compare(Foo? x, Foo? y)
    {
        return y!.Bar() - x!.Bar();
    }
}

I wished that I could declare the non-nullability already in the API.我希望我可以在 API 中声明不可为空性。

you can disable the warning if you are sure about nullability.如果您确定可空性,则可以禁用该警告。

#pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
    public int Compare(Foo x, Foo y)
#pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).

you can refer to this if you want to disable this on the project level.如果你想在项目级别禁用它,你可以参考这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM