Why isn't there "is not" keyword in c#?
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开发者_如何学C not X)
{
//Do my thing
}
How about the logical NOT operator !
, fits the description of the word 'not' just fine:
if (!(this is X))
{
//Do my thing
}
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 from GetType()
.
Both CodeInChaos and StriplingWarrior have reasonable explanations for why there isn't a not
keyword in C#.
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:
if (!(pero is Human)) ...
... 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.
Use good ol' bang symbol:
if (!(pero is Human))
{
}
BTW, is
is different, because it catches not only leaf derived class, but whole hierarchy of it, both interfaces and classes.
So, for
class Human: ICanSpeak, Mamal
{
...
}
Human h;
if (h is Human) { will be true }
if (h is ICanSpeak) { will be true }
if (h is Mamal) { will also be true }
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, whereas this 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 a not is
operator just doesn't offer enough.
You could implement an extension method, but I think that's stupid:
public static bool IsNot<T>(this object obj)
{
return !(obj is T);
}
精彩评论