我在确定数据容器时遇到了一些问题:
我需要保存一个key,value数组,这样我就可以通过索引访问数据了。
我开始时:
static Tuple<string, string>[] kv = {
Tuple.Create("K1", "V1"),
Tuple.Create("K2", "V2"),
Tuple.Create("K3", "V3"),
};
var index = 1;
Console.WriteLine(kv[index].Item1);
Console.WriteLine(kv[index].Item2);
另一方面,我可以简单地使用结构或类:
public struct KV
{
public string K;
public string V;
}
static KV[] kv =
{
new KV { K = "K1", V = "V1" },
// etc...
};
Console.WriteLine(kv[index].K);
Console.WriteLine(kv[index].V);
在结构/类方法上使用Tuple
有什么好处吗?或者是否有比上述更好的容器来保存这些数据?
答案 0 :(得分:1)
答案 1 :(得分:1)
在C#中创建自定义数据类型(类似于您所要求的)的常用方法是使用class
或struct
。
class Foo { int test; string name; }
struct Foo { int test; string name; }
var foo = new Foo() {test = 10, name = "some_name"};
正如您将注意到的,当我们需要在课堂上进行大量自定义时,这非常有用 - 属性,方法,属性等。但无数次,我们不需要所有的花边和装饰。我们只需要传递不同类型的多个变量
随着.NET Framework 2.0中LINQ的发布,anonymous type
类提供了具有简明语法的命名但只读属性,但这些类型仅限于在方法中使用,并且无法传递方法之间。
var foo = new {test = 10, name = "some_name" }
在.NET Framework 4.0中,他们提出了Tuple
结构。这里没有魔法,它只是一个预定义的通用结构。这个结构的变体有多达8个不同类型的成员。
var foo = new Tuple<int, string>(10, "some_name");
var foo = Tuple.Create(10, "some_name");
这种方法的明显局限性在于成员具有通用名称,如Item1
,Item2
等,这使得它不适合传输数据超长距离&#34;。而且好处是它非常简洁,没有不必要的开销。
使用最新版本的C#7,他们正在努力将匿名类型和元组的优点结合到可以在函数之间传递的匿名元组类型(称为ValueTuple
)。事实上,它们可以用简洁的语法隐式创建。
(test, name) Foo() {
return Bar()
}
(test, name) Bar() {
return (1, "new_name");
}
var allItems = new List<(int test, string name)>() {
(1, "some_name"),
(2, "new_name"),
}
有了这些背景,我强烈建议使用ValueTuple
作为容器来传递数据的数据结构,并在需要更多内容时编写明确的class
或struct
表达能力(属性,属性,方法等)
通常情况下,如果您的成员很少(比如少于5个),理想情况下是ValueType
,那么使用ValueTuple
struct
会获得性能优势。我不建议关注这方面,除非它是以性能为中心的应用程序。
<强>更新强>
为确保您可以使用ValueTuple
,您可能需要检查并确认一些事项。
System.ValueTuple
nuget软件包。没有使用条款来引用它。