gpt4 book ai didi

c# - 使用 is 运算符的变量初始化在使用相同的变量名时会出错

转载 作者:行者123 更新时间:2023-11-30 21:37:44 25 4
gpt4 key购买 nike

在使用 is 运算符检查类型时,我使用 C# 7.0 语法初始化变量。我想对所有场景使用相同的变量名,比如“动物”,如下所示:

// 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 { // ... }

但是,我收到一条错误消息,指出变量名称用于封闭范围。有办法解决这个问题吗?我真的不想为每个 else if 语句使用不同的变量名。

最佳答案

This page对正在发生的事情有一个很好的解释。基本上,正如错误指示的那样,初始化变量在 ifelse if 语句的封闭范围内可用。这类似于 out 参数的工作方式。所以,是的,当使用一系列 if 语句时,您只能使用一个变量名一次。

另一种方法是使用 switch 而不是 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;
}

switch 中初始化的变量被限制在它们的 case 范围内。 See also .

关于c# - 使用 is 运算符的变量初始化在使用相同的变量名时会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46941917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com