C#:'is' 关键字并检查 Not
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/811614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# : 'is' keyword and checking for Not
提问by Hugoware
This is a silly question, but you can use this code to check if something is a particular type...
这是一个愚蠢的问题,但您可以使用此代码来检查某些东西是否是特定类型...
if (child is IContainer) { //....
Is there a more elegant way to check for the "NOT" instance?
有没有更优雅的方法来检查“NOT”实例?
if (!(child is IContainer)) { //A little ugly... silly, yes I know...
//these don't work :)
if (child !is IContainer) {
if (child isnt IContainer) {
if (child aint IContainer) {
if (child isnotafreaking IContainer) {
Yes, yes... silly question....
是的,是的……愚蠢的问题……
Because there is some questionon what the code looks like, it's just a simple return at the start of a method.
因为有一些关于代码是什么样子的问题,所以它只是一个方法开始时的简单返回。
public void Update(DocumentPart part) {
part.Update();
if (!(DocumentPart is IContainer)) { return; }
foreach(DocumentPart child in ((IContainer)part).Children) {
//...etc...
采纳答案by Mehrdad Afshari
if(!(child is IContainer))
is the only operator to go (there's no IsNot
operator).
是唯一的操作符(没有IsNot
操作符)。
You can build an extension method that does it:
您可以构建一个扩展方法来做到这一点:
public static bool IsA<T>(this object obj) {
return obj is T;
}
and then use it to:
然后用它来:
if (!child.IsA<IContainer>())
And you could follow on your theme:
你可以关注你的主题:
public static bool IsNotAFreaking<T>(this object obj) {
return !(obj is T);
}
if (child.IsNotAFreaking<IContainer>()) { // ...
Update (considering the OP's code snippet):
更新(考虑 OP 的代码片段):
Since you're actually casting the value afterward, you could just use as
instead:
由于您实际上是在之后转换该值,因此您可以as
改为使用:
public void Update(DocumentPart part) {
part.Update();
IContainer containerPart = part as IContainer;
if(containerPart == null) return;
foreach(DocumentPart child in containerPart.Children) { // omit the cast.
//...etc...
回答by Mark Broadhurst
Why not just use the else ?
为什么不直接使用 else ?
if (child is IContainer)
{
//
}
else
{
// Do what you want here
}
Its neat it familiar and simple ?
它的整洁它熟悉而简单吗?
回答by BFree
Ugly? I disagree. The only other way (I personally think this is "uglier"):
丑陋的?我不同意。唯一的另一种方式(我个人认为这是“丑陋的”):
var obj = child as IContainer;
if(obj == null)
{
//child "aint" IContainer
}
回答by Muad'Dib
While the IS operator is normally the best way, there is an alternative that you can use in some cirumstances. You can use the as operator and test for null.
虽然 IS 运算符通常是最好的方法,但在某些情况下您可以使用替代方法。您可以使用 as 运算符并测试是否为空。
MyClass mc = foo as MyClass;
if ( mc == null ) { }
else {}
回答by Brian Rasmussen
The is
operator evaluates to a boolean result, so you can do anything you would otherwise be able to do on a bool. To negate it use the !
operator. Why would you want to have a different operator just for this?
该is
运营商计算结果为布尔结果,所以你可以做任何事情,否则你将能够在一个布尔做的。要否定它,请使用!
运算符。为什么要为此使用不同的运算符?
回答by Robert Cartaino
The way you have it is fine but you couldcreate a set of extension methods to make "a more elegant way to check for the 'NOT' instance."
您拥有它的方式很好,但您可以创建一组扩展方法来“以更优雅的方式检查 'NOT' 实例”。
public static bool Is<T>(this object myObject)
{
return (myObject is T);
}
public static bool IsNot<T>(this object myObject)
{
return !(myObject is T);
}
Then you could write:
然后你可以写:
if (child.IsNot<IContainer>())
{
// child is not an IContainer
}
回答by cjk
You can do it this way:
你可以这样做:
object a = new StreamWriter("c:\temp\test.txt");
if (a is TextReader == false)
{
Console.WriteLine("failed");
}
回答by Jeff
The extension method IsNot<T>
is a nice way to extend the syntax. Keep in mind
扩展方法IsNot<T>
是扩展语法的好方法。记住
var container = child as IContainer;
if(container != null)
{
// do something w/ contianer
}
performs better than doing something like
比做类似的事情表现更好
if(child is IContainer)
{
var container = child as IContainer;
// do something w/ container
}
In your case, it doesn't matter as you are returning from the method. In other words, be careful to not do both the check for type and then the type conversion immediately after.
在您的情况下,当您从该方法返回时并不重要。换句话说,注意不要同时检查类型,然后立即进行类型转换。
回答by Ternary
if (child is IContainer ? false : true)
回答by StriplingWarrior
While this doesn't avoid the problem of parentheses, for the sake of people getting here via Google, it should be mentioned that newer syntax exists (as of C# 7) to make the rest of your code a little cleaner:
虽然这并不能避免括号的问题,但为了人们通过 Google 到达这里,应该提到存在更新的语法(从 C# 7 开始)以使您的其余代码更简洁:
if (!(DocumentPart is IContainer container)) { return; }
foreach(DocumentPart child in container.Children) {
...
This avoids the double-cast, the null-check, and having a variable available in scopes where it could be null.
这避免了双重转换、空检查以及在可能为空的范围内使用变量。