我需要类似于 List<String, Int32, Int32>
的东西。List只支持一种类型,而Dictionary只支持两种类型。是否有一种干净的方式来做类似上面这样的事情(多维泛型列表/集合)?
我需要类似于 List<String, Int32, Int32>
的东西。List只支持一种类型,而Dictionary只支持两种类型。是否有一种干净的方式来做类似上面这样的事情(多维泛型列表/集合)?
最好的方法是为其创建一个容器,即一个类。
public class Container
{
public int int1 { get; set; }
public int int2 { get; set; }
public string string1 { get; set; }
}
那么在你需要的代码中
List<Container> myContainer = new List<Container>();
{get; set;}
代替。 - Robert PaulsonList<Tuple<String, Int32, Int32>>
。嗯,你不能在C# 3.0之前这样做,如果你可以使用C# 4.0,就像其他答案中提到的那样,使用元组。
但是在C# 3.0中 - 创建一个不可变结构
,并将所有类型的实例包装在结构中,并将结构类型作为泛型类型参数传递给列表。
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));
如果你好奇为什么要创建不可变的结构体 - 在这里查看。
struct MyStruct
{
int MyFirstInt;
int MySecondInt;
}
...
Dictionary<string, MyStruct> dictionary = ...