C# 7.0 中的元组文本是否可以启用面向方面的编程



我指的是元组文字,如下所述:https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/#comment-321926

喜欢元组字面意思。

但是,我预见到会大量查找返回元组中项目的顺序,并想知道我们如何解决这个问题。

例如,将元组中项目的名称作为标识定义方面而不是顺序不是更有意义吗?或者有没有办法做到这一点我没有看到?

例如:假设 NextEmployee(( 是一些我没有源代码的库方法,并且没有特别好的文档,假设它返回(firstname: “jamie”, lastname: “hince”, id: 102348)给我,我说:

(string lastname, var _, int __) = NextEmployee(); // I only need the last name

编译器要么很乐意将名字分配给姓氏,要么发出警告或错误。为什么不直接将姓氏映射到姓氏?

我会看到允许更松散耦合的架构,如果我们不必记住元组中的姓氏索引,并且可以要求像这样的方面"姓氏"。

元组只是一袋变量。作为变量,您可以分配任何可分配给变量类型的值,而不考虑变量名称。

名称只是变量名称的指示。返回值的唯一区别是编译器使用 TupleElementNames 属性保留元组元素的名称。

事实上,即使存在名称,编译器也会警告您,如果您不使用相同的名称,通常这是一个错误且仍然有效的语法:

(string firstname, string lastname, int id) NextEmployee()
=> (apples: "jamie", potatos: "hince", oranges: 102348);
/*
Warning CS8123 The tuple element name 'apples' is ignored because a different name is specified by the target type '(string firstname, string lastname, int id)'.
Warning CS8123 The tuple element name 'potatos' is ignored because a different name is specified by the target type '(string firstname, string lastname, int id)'.
Warning CS8123 The tuple element name 'oranges' is ignored because a different name is specified by the target type '(string firstname, string lastname, int id)'.
*/

您在此处使用的语法:

(string lastname, var _, int __) = NextEmployee();

不是元组声明语法,而是创建LastName变量、_变量和__变量的元组解构语法。

这些都是产生相同结果的等效项:

  • (var lastname, var _, var __) = NextEmployee(); // or any combination ofvarand type names
  • var (lastname, _, __) = NextEmployee();

若要声明元组以接收方法的返回,需要声明一个元组变量:

  • (string firstname, string lastname, int id) t = NextEmployee();
  • var t = NextEmployee();

但似乎您的意图是忽略LastNameid值:

(_, string lastname, _) = NextEmployee(); // declares a lastname variable and ignores firstname and id

但是如果你真的写(string lastname, _, _) = NextEmployee();,那么你正在为一个名为lastname的局部字符串变量分配返回的字符串"变量"的值firstname

请记住,元组不是实体。它们是一组值。如果您使用的库使用元组作为实体,请注意,该库可能有其他问题。

为什么不呢?好吧,因为底层运行时甚至不知道名称。

编译器必须在编译期间执行此操作。我们在哪里停下来?错别字、大写等呢? 在我看来,目前的方式还可以。

如果你对这个主题有不同的感觉,请在github上的官方语言设计仓库提出你的问题,提出一个问题:

https://www.github.com/dotnet/csharplang

保罗已经很好地解释了技术细节,所以我不打算重复。

最新更新