C#8 : Switch ref expressions

标签 c# ref c#-8.0 switch-expression

我不知道如何使 switch 表达式产生 ref 值。

bool cond = true;
int a = 1, b = 2;

// This works
ref int c = ref cond ? ref a : ref b;

// But using a switch expression fails to compile.
// Error CS1525 Invalid expression term 'ref'
c = ref (cond switch { true => ref a, false => ref b });

我的语法有错误吗?这可能吗?

无论我是否包含外部 ref ( ) 部分,它都不会编译。我使用 bool 只是为了快速说明问题,但我的实际用例并不那么简单。

最佳答案

是的,语法错误。由于您在问题(CS1525)中记下的编译器错误代码,这一点非常清楚。

为什么? switch 表达式似乎与 refs 不兼容。

不要与编译器对抗,只需以有效且易于阅读的方式编写代码即可。这是老式的编写方式:

ref int c = ref a;

if (!cond)
{
    c = ref b;
}

关于C#8 : Switch ref expressions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58985980/

相关文章:

javascript - 如何将动态值传递给 div 元素然后访问它 - React ?

reactjs - ref 在事件处理程序中没有值

c# - 谈论 C# 7.2 引用扩展方法时, "this ref"和 "ref this"有什么区别?

c# - 默认接口(interface)方法。现在,抽象类和接口(interface)之间有什么深刻意义的区别?

c# - 计算每个按钮的点击次数

c# - EF6 : Modifying an entity property with a foreign key relation - Do I need to change the Id or the related object or both?

c# - 如何在monogame中设置固定的窗口大小?

c# - 指针作为泛型类型参数

c# - 返回类型中引用类型的可空性与覆盖的成员不匹配

c# - C# 8 是否支持 .NET Framework?