.NET 的未来版本是否支持 C# 中的元组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/152019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Will a future version of .NET support tuples in C#?
提问by Graviton
.Net 3.5 doesn't support tuples. Too bad, But not sure whether the future version of .net will support tuples or not?
.Net 3.5 不支持元组。太糟糕了,但不确定 .net 的未来版本是否会支持元组?
采纳答案by Andreas Grech
I've just read this article from the MSDN Magazine: Building Tuple
我刚刚阅读了 MSDN 杂志上的这篇文章:Building Tuple
Here are excerpts:
以下是摘录:
The upcoming 4.0 release of Microsoft .NET Framework introduces a new type called System.Tuple. System.Tuple is a fixed-size collection of heterogeneously typed data. ? ?
即将发布的 Microsoft .NET Framework 4.0 版本引入了一种称为 System.Tuple 的新类型。System.Tuple 是固定大小的异构类型数据集合。? ?
?
?
Like an array, a tuple has a fixed size that can't be changed once it has been created. Unlike an array, each element in a tuple may be a different type, and a tuple is able to guarantee strong typing for each element.
与数组一样,元组具有固定大小,一旦创建就无法更改。与数组不同,元组中的每个元素可能是不同的类型,元组能够保证每个元素的强类型化。
?
?
There is already one example of a tuple floating around the Microsoft .NET Framework, in the System.Collections.Generic namespace: KeyValuePair. While KeyValuePair can be thought of as the same as Tuple, since they are both types that hold two things, KeyValuePair feels different from Tuple because it evokes a relationship between the two values it stores (and with good reason, as it supports the Dictionary class).
Furthermore, tuples can be arbitrarily sized, whereas KeyValuePair holds only two things: a key and a value.
在 System.Collections.Generic 命名空间中,已经有一个围绕 Microsoft .NET Framework 浮动的元组示例:KeyValuePair。虽然 KeyValuePair 可以被认为与 Tuple 相同,因为它们都是包含两个东西的类型,KeyValuePair 感觉与 Tuple 不同,因为它唤起了它存储的两个值之间的关系(并且有充分的理由,因为它支持 Dictionary 类)。
此外,元组可以任意大小,而 KeyValuePair 只保存两件事:一个键和一个值。
While some languages like F# have special syntax for tuples, you can use the new common tuple type from any language. Revisiting the first example, we can see that while useful, tuples can be overly verbose in languages without syntax for a tuple:
虽然某些语言(如 F#)对元组有特殊的语法,但您可以使用任何语言的新通用元组类型。回顾第一个例子,我们可以看到虽然有用,但元组在没有元组语法的语言中可能过于冗长:
class Program {
static void Main(string[] args) {
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
PrintStringAndInt(t.Item1, t.Item2);
}
static void PrintStringAndInt(string s, int i) {
Console.WriteLine("{0} {1}", s, i);
}
}
Using the var keyword from C# 3.0, we can remove the type signature on the tuple variable, which allows for somewhat more readable code.
使用 C# 3.0 中的 var 关键字,我们可以删除元组变量上的类型签名,这允许代码更具可读性。
var t = new Tuple<string, int>("Hello", 4);
We've also added some factory methods to a static Tuple class which makes it easier to build tuples in a language that supports type inference, like C#.
我们还在静态 Tuple 类中添加了一些工厂方法,这使得在支持类型推断的语言(如 C#)中构建元组变得更加容易。
var t = Tuple.Create("Hello", 4);
回答by dimarzionist
#region tuples
public class Tuple<T>
{
public Tuple(T first)
{
First = first;
}
public T First { get; set; }
}
public class Tuple<T, T2> : Tuple<T>
{
public Tuple(T first, T2 second)
: base(first)
{
Second = second;
}
public T2 Second { get; set; }
}
public class Tuple<T, T2, T3> : Tuple<T, T2>
{
public Tuple(T first, T2 second, T3 third)
: base(first, second)
{
Third = third;
}
public T3 Third { get; set; }
}
public class Tuple<T, T2, T3, T4> : Tuple<T, T2, T3>
{
public Tuple(T first, T2 second, T3 third, T4 fourth)
: base(first, second, third)
{
Fourth = fourth;
}
public T4 Fourth { get; set; }
}
#endregion
And to make declarations prettier:
并使声明更漂亮:
public static class Tuple
{
//Allows Tuple.New(1, "2") instead of new Tuple<int, string>(1, "2")
public static Tuple<T1, T2> New<T1, T2>(T1 t1, T2 t2)
{
return new Tuple<T1, T2>(t1, t2);
}
//etc...
}
回答by Tigraine
If I remember my Computer Science classes correctly tuples are just data.
如果我没记错我的计算机科学课程,元组就是数据。
If you want grouped data - create classes that contain properties. If you need something like the KeyValuePairthen there it is.
如果您想要分组数据 - 创建包含属性的类。如果您需要类似KeyValuePair 的东西,那么它就在那里。
回答by Merus
I'd be surprised - C# is a strongly-typed language, whereas tuples are suited for more dynamically typed languages. C# has been drifting more dynamic as time goes on, but that's syntactic sugar, not a real shift in the underlying data types.
我会感到惊讶 - C# 是一种强类型语言,而元组适用于更动态类型的语言。随着时间的推移,C# 变得更加动态,但这只是语法糖,而不是底层数据类型的真正转变。
If you want two values in one instance, a KeyValuePair<> is a decent substitute, albeit clumsy. You can also make a struct or a class that'll do the same thing, and is expandable.
如果你想在一个实例中使用两个值, KeyValuePair<> 是一个不错的替代品,尽管很笨拙。您还可以创建一个结构体或一个类来做同样的事情,并且是可扩展的。
回答by ChaosSpeeder
In my opinion, the anonymous types feature is not a tuple, but a very similar construct. The output of some LINQ Queries are collections of anonymous types, which behave like tuples.
在我看来,匿名类型特性不是一个元组,而是一个非常相似的结构。某些 LINQ 查询的输出是匿名类型的集合,其行为类似于元组。
Here is a statement, which creates a typed tuple :-) on the fly:
这是一个语句,它动态创建一个类型化的元组 :-):
var p1 = new {a = "A", b = 3};
see: http://www.developer.com/net/csharp/article.php/3589916
回答by Marc Gravell
C# supports simple tuples via generics quite easily (as per an earlier answer), and with "mumble typing" (one of many possible C# language enhancements) to improve type inference they could be very, very powerful.
C# 很容易通过泛型支持简单的元组(根据之前的答案),并且通过“mumble 类型”(许多可能的 C# 语言增强之一)来改进类型推断,它们可能非常非常强大。
For what it is worth, F# supports tuples natively, and having played with it, I'm not sure that (anonymous) tuples add much... what you gain in brevity you lose veryquickly in code clarity.
对于什么是值得,F#支持原生的元组,并且已经打了它,我不知道这(匿名)元组增加多少...你在简洁收获了什么你失去非常的代码清晰快速。
For code within a single method, there are anonymous types; for code going outside of a method, I think I'll stick to simple named types. Of course, if a future C# makes it easier to make these immutable (while still easy to work with) I'll be happy.
对于单个方法中的代码,有匿名类型;对于超出方法的代码,我想我会坚持使用简单的命名类型。当然,如果未来的 C# 可以更轻松地使这些不可变(同时仍然易于使用),我会很高兴。
回答by Chris Ballard
Implementing Tuple classes or reusing F# classes within C# is only half the story - these give you the ability to create tuples with relative ease, but not really the syntactic sugar which makes them so nice to use in languages like F#.
在 C# 中实现 Tuple 类或重用 F# 类只是故事的一半 - 这些使您能够相对轻松地创建元组,但并不是真正的语法糖,使它们在 F# 等语言中使用起来非常好。
For example in F# you can use pattern matching to extract both parts of a tuple within a let statment, eg
例如,在 F# 中,您可以使用模式匹配在 let 语句中提取元组的两个部分,例如
let (a, b) = someTupleFunc
Unfortunately to do the same using the F# classes from C# would be much less elegant:
不幸的是,使用 C# 中的 F# 类做同样的事情会不那么优雅:
Tuple<int,int> x = someTupleFunc();
int a = x.get_Item1();
int b = x.get_Item2();
Tuples represent a powerful method for returning multiple values from a function call without the need to litter your code with throwaway classes, or resorting to ugly ref or out parameters. However, in my opinion, without some syntactic sugar to make their creation and access more elegant, they are of limited use.
元组代表了一种强大的方法,可以从函数调用中返回多个值,而无需在代码中放置一次性类,或者诉诸丑陋的 ref 或 out 参数。然而,在我看来,如果没有一些语法糖来使它们的创建和访问更加优雅,它们的用途是有限的。
回答by Chris Ballard
To make these useful in a hashtable or dictionary, you will likely want to provide overloads for GetHashCode and Equals.
为了使它们在哈希表或字典中有用,您可能需要为 GetHashCode 和 Equals 提供重载。
回答by Lasse V. Karlsen
Here's my set of tuples, they're autogenerated by a Python script, so I've perhaps gone a bit overboard:
这是我的一组元组,它们是由 Python 脚本自动生成的,所以我可能有点过分了:
You'll need a username/password, they're both guest
你需要一个用户名/密码,他们都是来宾
They are based on inheritance, but Tuple<Int32,String>
will not compare equal to Tuple<Int32,String,Boolean>
even if they happen to have the same values for the two first members.
它们基于继承,但即使它们的前两个成员碰巧具有相同的值,Tuple<Int32,String>
也不会比较相等Tuple<Int32,String,Boolean>
。
They also implement GetHashCode and ToString and so forth, and lots of smallish helper methods.
它们还实现了 GetHashCode 和 ToString 等,以及许多小型辅助方法。
Example of usage:
用法示例:
Tuple<Int32, String> t1 = new Tuple<Int32, String>(10, "a");
Tuple<Int32, String, Boolean> t2 = new Tuple<Int32, String, Boolean>(10, "a", true);
if (t1.Equals(t2))
Console.Out.WriteLine(t1 + " == " + t2);
else
Console.Out.WriteLine(t1 + " != " + t2);
Will output:
将输出:
10, a != 10, a, True
回答by Rinat Abdullin
There is a proper(not quick) C# Tupleimplementation in Lokad Shared Libraries(Open-source, of course) that includes following required features:
Lokad 共享库(当然是开源的)中有一个适当的(不是快速的)C# 元组实现,其中包括以下必需的功能:
- 2-5 immutable tuple implementations
- Proper DebuggerDisplayAttribute
- Proper hashing and equality checks
- Helpers for generating tuples from the provided parameters (generics are inferred by compiler) and extensions for collection-based operations.
- production-tested.
- 2-5 个不可变元组实现
- 正确的 DebuggerDisplayAttribute
- 正确的散列和相等性检查
- 从提供的参数生成元组的助手(编译器推断泛型)和基于集合的操作的扩展。
- 生产测试。