C# 使用is运算符初始化变量在使用相同变量名时出错
在使用C# 使用is运算符初始化变量在使用相同变量名时出错,c#,scope,operators,c#-7.0,C#,Scope,Operators,C# 7.0,在使用is运算符检查类型时,我使用C#7.0语法初始化变量。我想对所有场景使用相同的变量名,比如“animal”,如下所示: // Yes, polymorphism may be better. This is just an illustration. if (item is Dog animal) { // ... } else if (item is Cat animal) { // ... } else if (item is Animal animal) { // ... } els
is
运算符检查类型时,我使用C#7.0语法初始化变量。我想对所有场景使用相同的变量名,比如“animal”,如下所示:
// Yes, polymorphism may be better. This is just an illustration.
if (item is Dog animal) { // ... }
else if (item is Cat animal) { // ... }
else if (item is Animal animal) { // ... }
else { // ... }
但是,我得到一个错误,该错误表示变量名在封闭范围内使用。有没有办法绕过这个问题?我真的不想对每个语句使用不同的变量名,否则如果语句发生了什么,我就不想使用不同的变量名。很好地解释了发生了什么。基本上,正如错误所示,初始化变量在if
和else if
语句的封闭范围内可用。这类似于out
参数的工作方式。因此,是的,当使用一系列if
语句时,变量名只能使用一次
如果
,另一种选择是使用开关
,而不是:
switch (item) {
case Dog animal:
// ...
break;
case Cat animal:
// ...
break;
case Animal animal:
// ...
break;
default:
// Interestingly, you cannot reuse the variable name here.
// But you could create a new scope and then reuse it.
{
Animal animal = ...
}
break;
}
在开关
中初始化的变量仅限于其案例
的范围