"x as X!= null"和"x is X"是否总是返回相同的结果?

aKz*_*enT 3 .net c# operators type-conversion comparison-operators

是否存在这两个if语句会产生不同结果的情况?

if(x as X != null)
{
  // Do something
}

if(x is X)
{
  // Do something
}
Run Code Online (Sandbox Code Playgroud)

编辑:澄清:我知道运营商(一般)和他们的意思有什么区别.问题是,是否存在这两种情况会产生不同结果的情况.

Jar*_*Par 6

功能上两个语句之间没有区别.通常,该as版本用于避免双重类型测试,因为您可以执行以下操作

var local = x as X;
if (local != null) { 
  // Sweet I have local! 
}
Run Code Online (Sandbox Code Playgroud)

if (x is X) { 
  // This runs the type check yet again 
  var local = (X)x; 
}
Run Code Online (Sandbox Code Playgroud)

如果您在类型测试后实际上没有使用该值,那么只需使用该is版本