C# 7.0 元组推断

9
当我写下这行代码时:
Tuple<string,string> key = (controller, action);

我遇到了这个错误:

Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type '(string controller, string action)' to 'System.Tuple' Project.Web PageMetadata.cs 27 Active

这似乎是C#7更新中新元组增强功能的一种直观应用,但它却不能正常工作。我做错了什么?
4个回答

12

新的元组功能需要 ValueTuple 类型。

ValueTuple<string, string> key = (controller, action);
var key = (controller, action);

值得注意的是,Tuple 是一个类,而 ValueTuple 是一个结构体。您不应该混淆它们。有关 C# 7 中新元组功能的更多详细信息,请参见此处


2

首先,你会遇到这个错误是因为你试图将新样式元组(ValueTuple)转换为旧样式元组(Tuple)。

可以使用ToTuple()扩展方法来实现:

Tuple<string,string> key = (controller, action).ToTuple();        

但这可能不是你想要做的。如果你想创建一个新元组实例,可以这样做:

ValueTuple<string,string> key = (controller, action);

但是如果你那样做,你最终仍然会得到两个元素被称为Item1Item2,这违背了新元组语法的一个关键特性:命名元素。将其更改为使用var,然后你就可以获得命名元素:

var key = (controller, action);
Console.WriteLine(key.controller); // key.controller is now valid

如果您真的不喜欢使用var(有些人确实不喜欢),那么您可以用长格式表达它,以仍然获得这些命名元素:

(string controller, string action) key = (controller, action); 
Console.WriteLine(key.controller);

0

0
如果你真的需要将 System.Tuple 转换为 System.ValueTuple(元组语法使用的类型),或者反过来,可以使用扩展方法:ToTupleToValueTuple。这些方法适用于小元数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接