为什么没有“不是”呢? C# 中的关键字?
有时检查一个对象是否不是 X 类型是有意义的,因此您需要这样做:
if(this.GetType() != typeof(X))
{
//Do my thing.
}
在我看来,这有点麻烦,这样的事情不是更好吗:
if(this is not X)
{
//Do my thing
}
It just makes sense sometimes to check if an object is not type of X, so you need to do this instead:
if(this.GetType() != typeof(X))
{
//Do my thing.
}
Which is a bit cumbersome to my opinion, would not something like this be nicer:
if(this is not X)
{
//Do my thing
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
逻辑 NOT 运算符
!
怎么样,非常适合“not”这个词的描述:正如其他人指出的那样,
is
也用于检查对象是否类继承某个类或实现某个接口,这与GetType()
有很大不同。CodeInChaos 和 StriplingWarrior 对于为什么没有
not
关键字。How about the logical NOT operator
!
, fits the description of the word 'not' just fine:As others have pointed out though,
is
is also used to check if an object's class inherits from some class or implements some interface, which is rather different fromGetType()
.Both CodeInChaos and StriplingWarrior have reasonable explanations for why there isn't a
not
keyword in C#.向语言添加关键字会增加复杂性。在初始规范之后向语言添加关键字可能会导致人们升级时发生重大变化。因此,通常只有在有非常充分的理由时才会添加关键字。在这种情况下,正如其他答案所指出的,使用 bang 运算符非常容易:
...典型的 C# (/C/C++/Java) 开发人员会读到“if not (pero is human)”。因此,没有太多理由使用特殊关键字。
Adding a keyword to a language adds complexity. Adding a keyword to a language after the initial specification could cause breaking changes for people upgrading. So keywords generally only get added if there's a very strong case for them. In this case, as the other answers point out, it is very easy to use the bang operator:
... which a typical C# (/C/C++/Java) developer would read "if not (pero is human)". So there's not much justification for a special keyword.
使用好的 ol' bang 符号:
顺便说一句,
is
是不同的,因为它不仅捕获叶派生类,还捕获它的整个层次结构,包括接口和类。所以,对于
Use good ol' bang symbol:
BTW,
is
is different, because it catches not only leaf derived class, but whole hierarchy of it, both interfaces and classes.So, for
请注意,如果 this 派生自(或在接口类型的情况下实现)但与 X 不同,则
this.GetType()
!=typeof(X)
返回 false,而this is X
返回 true。当您可以只使用
!(a is X)
时,为什么还要有一个单独的关键字呢?这使得语言变得臃肿而收效甚微。正如 Eric Lippert 喜欢强调的那样,每一个新的语言功能都需要提供足够的优势来弥补编码、文档、测试,当然还有语言增加的复杂性。而not is
运算符提供的功能还不够。你可以实现一个扩展方法,但我认为这是愚蠢的:
Note that
this.GetType()
!=typeof(X)
returns false if this is derived from (or implements in case of an interface type) but not identical to X, whereasthis is X
returns true.And why would there be a separate keyword when you can just use
!(a is X)
? That's bloating the language with little gain. As Eric Lippert likes to stress every new language feature needs to offer enough advantages to compensate for coding, documenting, testing and of course the increased complexity of the language. And anot is
operator just doesn't offer enough.You could implement an extension method, but I think that's stupid: