为什么变量名称作为下划线字符(“ _”)不能用于解构

巨大CK

我已将变量声明为下划线字符,_如下所示,并且编译器能够顺利执行代码。

 int _ = 10;
 _ += 10;

 onsole.WriteLine(_);

但是,_对于下面显示Deconstruction语法,编译器没有检测到名为下划线字符的变量

(string _, int age) = new Student("Vimal", "Heaven", 20);

同时,编译器和Visual Studio intellisense会_为下面显示的另一种语法检测名为下划线的变量

var student  = new Student("Vimal", "Heaven", 20);
(string _, int age) details = student.GetDetails();

Console.WriteLine(details._);

我了解没有人使用下划线字符来命名变量。为什么编译器在处理下划线_字符时不一致

我不在discards这里讨论C#

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);
}
清扫器

为什么编译器在处理下划线_字符时不一致?

在前三个代码段中,每个_字符的解释方式都不同。

这里:

(string _, int age) details = student.GetDetails();

(string _, int age)在语法上是变量类型details,而变量名details不是__是类型名称的一部分,特别是元组字段名称

文档(重点是我的):

通过为变量分配下划线(_)作为其名称,可以表明该变量是丢弃变量

因此,_输入(string _, int age) details不是丢弃。这就是为什么您可以按来访问它的原因details._

在同一页面的后面:

在C#7.0中,以下情况下的分配中支持丢弃:

  • 元组和对象解构。
  • 模式与is和switch匹配。
  • 调用没有参数的方法。
  • 没有_范围时的独立_。

您在这里的情况:

int _ = 10; 
_ += 10;

Console.WriteLine(_);

不在列表中,因此丢弃不适用。在第一行中,它不是“独立_”,_也不是丢弃,因此您声明了一个名为的变量_在以下各行中,存在_in范围,因为您在第一行中声明了具有该名称的变量。

您显示的第二个代码段:

(string _, int age) = new Student("Vimal", "Heaven", 20);

是在列表中的“元组和对象解构”,因此这次_被视为丢弃,并且这次它没有声明名为的变量_

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章