使用 is 与特定类型和 var 有什么区别?

问题描述 投票:0回答:1

这两个代码片段有什么区别?带有

var
的一个可以工作,但是带有 string 类型的一个会出错。(使用未分配的变量错误)它们不是都在运行时才分配吗?我对这些变量的分配方式和位置感到非常困惑。努力区分运行时和编译时计算。 第一个代码:

 object x = "Message";
 bool result = x is string o;
 Console.WriteLine(o);

第二个代码:

 object x = "Message";
 bool result = x is var o;
 Console.WriteLine(o);

第二个有效,第一个给出了我之前提到的错误。

c# var
1个回答
0
投票

如果你想比较'x'变量的类型,你应该使用'is {type}'

object x = "Message";
bool result = x is string;

如果您想使用“x is var y”模式,您需要在布尔表达式中使用临时变量

object x = "Message";
bool result = x is var o;
Console.WriteLine(o);

有关“x is var y”模式的更多信息,您可以在下面找到:

C# 7 中 Var 模式的使用

© www.soinside.com 2019 - 2024. All rights reserved.