[英]IEquatable<T> and [AllowNull]
I just updated Visual Studio to latest 16.6.0 Preview 1.0 with latest .NET Core 3.1.2.我刚刚使用最新的 .NET Core 3.1.2 将 Visual Studio 更新到最新的 16.6.0 Preview 1.0。 My project has
<Nullable>enable</Nullable>
.我的项目有
<Nullable>enable</Nullable>
。
It seems there has been a change to IEquatable<T>
and now it is defined with [AllowNull]
:似乎
IEquatable<T>
发生了变化,现在它是用[AllowNull]
定义的:
public interface IEquatable<T>
{
bool Equals([AllowNull] T other);
}
As a result, any class of mine which implemented IEquatable<T>
with bool Equals(T o)
now shows a warning:因此,我的任何使用
bool Equals(T o)
实现IEquatable<T>
类现在都会显示警告:
CS8767
: Nullability of reference types in type of parameter 'o' of 'bool MyType.Equals(MyType o)' doesn't match implicitly implemented member 'bool IEquatable.Equals(MyType other)' because of nullability attributes.CS8767
:由于可空性属性,“bool MyType.Equals(MyType o)”的参数“o”类型中的引用类型的可空性与隐式实现的成员 'bool IEquatable.Equals(MyType other)' 不匹配。
What is the best way to solve this ?解决这个问题的最佳方法是什么?
I can add a nullable operator bool Equals(T? o)
, or I can add [AllowNull]
(with reference to System.Diagnostics.CodeAnalysis
).我可以添加一个可为空的运算符
bool Equals(T? o)
,或者我可以添加[AllowNull]
(参考System.Diagnostics.CodeAnalysis
)。 Both seem to make the warning go away, but I'm not sure which one is better.两者似乎都使警告消失,但我不确定哪个更好。
Also, I now opened the door for a null
parameter which I didn't really want.此外,我现在为一个我并不真正想要的
null
参数打开了大门。
The convention for IEquatable<T>.Equals
is that the argument can be null. IEquatable<T>.Equals
是参数可以为 null。 If T
is a reference type, just annotate it with ?
如果
T
是引用类型,只需用?
and the warning will go away.并且警告将消失。 The following compiles just fine:
以下编译就好了:
#nullable enable
using System;
public class C1 : IEquatable<C1>
{
public bool Equals(C1? c) => false;
}
public struct C2 : IEquatable<C2>
{
public bool Equals(C2 c) => false;
}
https://sharplab.io/#v2:EYLgtghgzgLgpgJwD4GIB2BXANliwtwAEcaeBAsAFBUACATAIxW0DMh9hAwg4SIQJIBRAI4YIMMnAA83AHxUA3lUIr2bYAHsNWQiLFYoACm4B+QgGMAlIQC8swgDMIBuAG4qAX2aUabWAgxzGC46XgE9cUkZOnlKJUpVNUJNbV1RZyNOUKtbeycXd0ovSiA= https://sharplab.io/#v2:EYLgtghgzgLgpgJwD4GIB2BXANliwtwAEcaeBAsAFBUACATAIxW0DMh9hAwg4SIQJIBRAI4YIMMnAA83AHxUA3lUIr2bYAHsNWQiLFYoACm4B+QgGMAlIQC8swgDMIBuAG4qAX2aUabWAgxzGC46XgE9cUkZOnlKJUpVNUJNbV1RZyNOUKtbeycXd0ovSiA=
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.