7

我需要类似的东西List<String, Int32, Int32>。List 一次只支持一种类型,而 Dictionary 一次只支持两种。有没有一种干净的方法来做类似上面的事情(多维通用列表/集合)?

4

4 回答 4

14

最好的方法是为它创建一个容器,即一个类

public class Container
{
    public int int1 { get; set; }
    public int int2 { get; set; }
    public string string1 { get; set; }
}

然后在你需要的代码中

List<Container> myContainer = new List<Container>();
于 2010-06-08T04:51:38.633 回答
13

在 .NET 4 中,您可以使用List<Tuple<String, Int32, Int32>>.

于 2010-06-08T04:50:50.757 回答
1

好吧,在 C# 3.0 之前你不能这样做,如果你可以使用其他答案中提到的 C# 4.0,请使用元组。

但是在 C# 3.0 中 - 在结构中创建Immutable structure并包装所有类型的实例,并将结构类型作为泛型类型参数传递给您的列表。

public struct Container
{
    public string String1 { get; private set; }
    public int Int1 { get; private set; }
    public int Int2 { get; private set; }

    public Container(string string1, int int1, int int2)
        : this()
    {
        this.String1 = string1;
        this.Int1 = int1;
        this.Int2 = int2;
    }
}

//Client code
IList<Container> myList = new List<Container>();
myList.Add(new Container("hello world", 10, 12));

如果你很好奇为什么要创建不可变结构 -在这里结帐

于 2010-06-08T04:56:38.557 回答
0

根据您的评论,听起来您需要一个结构,其中两个整数存储在带有字符串键的字典中。

struct MyStruct
{
   int MyFirstInt;
   int MySecondInt;
}

...

Dictionary<string, MyStruct> dictionary = ...
于 2010-06-08T04:59:33.997 回答