Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用is运算符初始化变量在使用相同变量名时出错_C#_Scope_Operators_C# 7.0 - Fatal编程技术网

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;
}
开关
中初始化的变量仅限于其
案例
的范围