我已将变量声明为下划线字符,_
如下所示,并且编译器能够顺利执行代码。
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] 删除。
我来说两句