gpt4 book ai didi

C#8.0 switch 语句和局部变量

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:08 24 4
gpt4 key购买 nike

为了了解 switch 语句的新 C#8.0 语法的限制,我正在尝试将一些旧代码从 C#7.0 转换为 C#8.0。我想使用本地引入的变量(模式匹配),但显然我做错了什么。

供引用,propertySelectorExpression类型为 Expression<Func<TObject, TProperty>> propertySelectorExpression

旧代码:

PropertyInfo propertyInfo = null;
switch (propertySelectorExpression.Body)
{
case MemberExpression me:
propertyInfo = me.Member as PropertyInfo;
break;
case UnaryExpression ue:
propertyInfo = (ue.Operand as MemberExpression)?.Member as PropertyInfo;
break;
}

新代码(尝试,不编译):

PropertyInfo propertyInfo = null;
propertyInfo = switch (propertySelectorExpression.Body)
{
MemberExpression me => me.Member as PropertyInfo,
UnaryExpression ue => (ue.Operand as MemberExpression)?.Member as PropertyInfo
}

PropertyInfo propertyInfo = null;
switch (propertySelectorExpression.Body)
{
MemberExpression me => propertyInfo = me.Member as PropertyInfo,
UnaryExpression ue => propertyInfo = (ue.Operand as MemberExpression)?.Member as PropertyInfo
}

我做错了什么或假设错了什么?

最佳答案

您混淆了 switch 的两种用法的语法.

你有:

  • switch 语句
  • 切换表达式

开关表达式的语法是<expression> switch { <patterns> } ,所以这应该编译:

PropertyInfo propertyInfo = null;
propertyInfo = propertySelectorExpression.Body switch // <-- noticed the switched order
{
MemberExpression me => me.Member as PropertyInfo,
UnaryExpression ue => (ue.Operand as MemberExpression)?.Member as PropertyInfo
}

(尽管编译器会警告您 switch 表达式无法处理所有可能的输入)

switch 语句(您问题中的最后一个代码示例)的语法使用 case而不是 lambda 语法,所以这应该编译:

PropertyInfo propertyInfo = null;
switch (propertySelectorExpression.Body)
{
case MemberExpression me:
propertyInfo = me.Member as PropertyInfo;
break;
case UnaryExpression ue:
propertyInfo = (ue.Operand as MemberExpression)?.Member as PropertyInfo;
break;
}

关于C#8.0 switch 语句和局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59248356/

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