C#中的不是运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2380436/
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
IS NOT operator in C#
提问by Tomas
I can't find the "is not" operator in C#.
For example I have the code below which does not work. I need to check that err
is not of type class ThreadAbortException
.
我在 C# 中找不到“不是”运算符。例如,我有下面的代码不起作用。我需要检查它err
不是 class 类型ThreadAbortException
。
catch (Exception err)
{
if (err is not ThreadAbortException)
{
}
}
采纳答案by Lee
Just change the catch block to:
只需将 catch 块更改为:
catch(ThreadAbortException ex)
{
}
catch(Exception ex)
{
}
so you can handle ThreadAbortExceptions and all others separately.
因此您可以分别处理 ThreadAbortExceptions 和所有其他异常。
回答by Nick Craver
In this case, wrap and check the boolean opposite:
在这种情况下,包装并检查相反的布尔值:
if (!(err is ThreadAbortException))
回答by Mark Carpenter
You should be able to do something like this:
你应该能够做这样的事情:
catch (Exception err){
if (!(err is ThreadAbortException)) {
//Code
}
}
回答by Nick
More than likely what you ought to do in this circumstance is:
在这种情况下,您应该做的很可能是:
try
{
// Do Something
}
catch (ThreadAbortException threadEx)
{
// Do something specific
}
catch (Exception ex)
{
// Do something more generic
}
You can have multiple catch
blocks for a try
. Always make sure to order them such that the most specific is on top, and the most generic (catch (Exception ex)
) is last because the lookup order is from top to bottom, so if you put the catch (Exception ex)
first, it will always be the only one to run.
你可以有多个catch
的块try
。始终确保对它们进行排序,使最具体的放在最上面,最通用的 ( catch (Exception ex)
)放在最后,因为查找顺序是从上到下的,因此如果您放置第catch (Exception ex)
一个,它将始终是唯一运行的。
回答by Pharabus
Lee has the best answer.
李有最好的答案。
Just to add, you should always catch from the most specific down to the most general. In your case the ThreadAbortException
is the most specific so deal with that first.
补充一点,你应该总是从最具体的到最一般的。在您的情况下,这ThreadAbortException
是最具体的,因此请先处理。
回答by Usman Akram
Perhaps you are looking for this:
也许你正在寻找这个:
if(err.GetType() != typeof(ThreadAbortException))
{
}
But I strongly recommendusing a separate catch statement, as suggested by Lee.
但是我强烈建议按照 Lee 的建议使用单独的 catch 语句。
catch(ThreadAbortException ex)
{
}
catch(Exception ex)
{
}