C# 是否有类似列表的内容<;字符串,Int32,Int32>;(多维通用列表)
我需要类似于C# 是否有类似列表的内容<;字符串,Int32,Int32>;(多维通用列表),c#,list,collections,generic-list,C#,List,Collections,Generic List,我需要类似于列表的东西。列表一次只支持一种类型,而字典一次只支持两种类型。有没有一种干净的方法可以完成上述操作(多维泛型列表/集合)?在.NET4中,您可以使用列表最好的方法是为它创建一个容器,即类 public class Container { public int int1 { get; set; } public int int2 { get; set; } public string string1 { get; set; } } 然后在需要它的代码中 Lis
列表的东西。列表一次只支持一种类型,而字典一次只支持两种类型。有没有一种干净的方法可以完成上述操作(多维泛型列表/集合)?在.NET4中,您可以使用列表
最好的方法是为它创建一个容器,即类
public class Container
{
public int int1 { get; set; }
public int int2 { get; set; }
public string string1 { get; set; }
}
然后在需要它的代码中
List<Container> myContainer = new List<Container>();
List myContainer=new List();
好吧,在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));
公共结构容器
{
公共字符串String1{get;private set;}
public int Int1{get;private set;}
public int Int2{get;private set;}
公共容器(字符串string1、int-int1、int-int2)
:此()
{
此参数为0.String1=String1;
this.Int1=Int1;
this.Int2=Int2;
}
}
//客户端代码
IList myList=新列表();
Add(新容器(“helloworld”,10,12));
如果您想知道为什么要根据您的注释创建不可变结构-。,那么听起来您需要一个包含两个整数的结构,并使用字符串键存储在字典中
struct MyStruct
{
int MyFirstInt;
int MySecondInt;
}
...
Dictionary<string, MyStruct> dictionary = ...
struct MyStruct
{
int MyFirstInt;
int MySecondInt;
}
...
字典=。。。
Int32的复制很有趣。你想做什么?我必须在语义上将两个不同的数字与一个字符串相关联,然后用这个字符串在视图中呈现数据。我认为@Alex有像我这样的java背景。不幸的是,我在.NET 3.5上,但我会在4.0中记住这一点+1,因为它不需要.Net4元组,并且可以通过类实现,但是-1,因为您应该避免类上的公共字段。作为属性实现,并改用simple{get;set;}
。您可能需要重写Equals,GetHashCode tootype容器应该是一个不可变的结构,因为它只表示值。根据Alex的实现需要,他可以决定是否需要Equals to,还可以决定Class Vs struct,同样取决于他的项目的需要,但是如果它只是用于存储值,那么结构就有意义了。