我已将变量声明为下划线字符 _
像下面这样,编译器能够顺利执行代码。
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/