首页 > 解决方案 > c# 7.0 tuple 用作自定义类型

问题描述

我有一个 C# 7.0 元组声明,例如:

(int ID, string name, string secondName, int age) foo = (19,"Harry", "Potter", 8);

每次声明一个新的 var 或者我在函数/方法中使用它时,我都需要重写整个声明。例如:

private (int ID, string name, string secondName, int age) DoSomething((int ID, string name, string secondName, int age) passElement) {...

我想将它用作自定义类型并编写如下内容:

私人MyType DoSomething(我的类型passedElement){...

对于传统的元组,我总是使用:

使用 MyType = System.Tuple< int, string, string, int>;

它工作正常,但如果我尝试使用:

使用 MyType = (int ID, string name, string secondName, int age);

智能感知给我一个错误“预期标识符”,强调等号右侧的部分。

如果有的话,正确的声明方式是什么?

先感谢您。

标签: variablestuplesdeclarationusingc#-7.0

解决方案


元组不是类型。不是通常意义上的。

C# 中的元组被创建为充当单个值的包。

指定的元组元素名称不是类型的一部分,而是从该定义创建的实例上的注释。对于运行时(以及大部分情况下的编译器),(int ID, string name, string secondName, int age)它与(int i1, string s1, string s2, int i2)or相同(int, string, string, int)


推荐阅读