c# - 为什么变量名作为下划线字符 ("_")不适用于解构

标签 c# .net-core .net-core-3.1

我已将变量声明为下划线字符 _像下面这样,编译器能够顺利执行代码。

 int _ = 10;
 _ += 10;

 onsole.WriteLine(_);
但是,编译器没有检测到名为下划线字符的变量 _对于 Deconstruction语法如下所示。
(string _, int age) = new Student("Vimal", "Heaven", 20);
同时,编译器和 Visual Studio 智能感知检测到名为下划线的变量 _对于下面显示的另一种语法。
var student  = new Student("Vimal", "Heaven", 20);
(string _, int age) details = student.GetDetails();

Console.WriteLine(details._);
我知道没有人使用下划线字符来命名变量。为什么编译器在处理下划线时不一致 _特点?
我不是在讨论 C# discards这里。Student样本中提到的类。
public class Student
{
    public string Name { get; set; }
    public string Address { get; set; }
    public int Age { get; set; }

    public Student(string name, string address, int age = 0) => (Name, Address, Age) = (name, address, age);

    public void Deconstruct(out string name, out int age) => (name, age) = (Name, Age);
    public (string, int) GetDetails() => (Name, Age);
}

最佳答案

Why compiler is inconsistent in handling the underscore _ character?


在前三个代码片段中的每一个中,_字符以不同的方式解释。
这里:
(string _, int age) details = student.GetDetails();
(string _, int age)在语法上是变量 details 的类型,变量名是 details ,不是 _ . _是类型名称的一部分,特别是 tuple field name .
来自 docs (强调我的):

You indicate that a variable is a discard by assigning it the underscore (_) as its name.


所以_(string _, int age) details不是丢弃。这就是为什么您可以通过 details._ 访问它.
稍后在同一页面中:

In C# 7.0, discards are supported in assignments in the following contexts:

  • Tuple and object deconstruction.
  • Pattern matching with is and switch.
  • Calls to methods with out parameters.
  • A standalone _ when no _ is in scope.

你这里的情况:
int _ = 10; 
_ += 10;

Console.WriteLine(_);
不在列表中,因此丢弃在那里不适用。在第一行,它不是“一个独立的 _”,所以 _不是丢弃,并且您声明了一个名为 _ 的变量.在以下几行中,有一个 _在范围内,因为您在第一行声明了一个具有该名称的变量。
您展示的第二个代码片段:
(string _, int age) = new Student("Vimal", "Heaven", 20);
是“元组与对象解构”,上榜了,所以这次_被视为丢弃,这次它没有声明一个名为 _ 的变量.

关于c# - 为什么变量名作为下划线字符 ("_")不适用于解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63989930/

相关文章:

c# - Task 与 Task<TResult> 的不同行为

c# - 如何在 ASP.NET Core 中启用跟踪日志记录?

azure - 如何获取 CreateItemQuery 返回的项目的 ETag 值

c# - System.Reflection.AmbiguousMatchException : 'Ambiguous match found.'

c# - 启动服务未返回有关失败的足够信息

c# - 在 C# (.NET) 中是否有任何函数可以相应地比较字符串的长度?

c# - 在 N 层应用程序中使用 DTO 时的 OrderBy

c# - 通过具有多对多关系的 Entity Framework 代码优先方法播种 SQL Server

Wcf 服务在 .NET Core 3.1 控制台应用程序中工作,但在 ASP.NET Core 3.1 Web API 中无法工作

c# - 为什么 File.ReadAllLinesAsync() 会阻塞 UI 线程?