c#如何最好地将数组或列表放入同样有名称的类中



我没有用我以前的非OOP方式,而是尝试做人们认为最好的事情。我需要存储大约9个不同长度的Int数组。我还需要将它们与字符串名称"相关联;这被称为"等等";我认为将所有这些存储到一个类对象中是有意义的,这样我以后就可以干净地对它们进行迭代,而无需使用相同的for循环迭代器查找两个不同的位置。

示例:

public class Thing
{
public List<int> SDNA {get; set;}
public string Name {get; set;}   
}
List<Thing> things = new List<Thing>
{
new Thing { SDNA = {2,4,5,7,9,11},Name = "First Thing"}
}

我得到了一个null ref异常(我假设它是类中列表的原因(。我试图用这种方式创建一个列表来清除null ref,但它有一些其他错误。

List<Thing> things = new List<Thing>();
things.Add(new Thing() {SDNA = {2,4,5,7,9,11},Name = "The first things name"});

无效令牌的错误等。我应该只使用两个不同的存储数组来完成它吗?一个用于名称,一个用于Ints的锯齿状数组,然后分别引用它们?我觉得很难看。为什么我不能把它们都放在一个东西里呢?

谢谢!

最简单的情况下如果您只想拥有名称到值(数组(的关联,可以尝试使用简单的Dictionary,例如

private Dictionary<string, List<int>> things = new Dictionary<string, List<int>>() {
{"First thing", new List<int>() {2, 4, 5, 7, 9, 11}},
};

然后你可以用

// Add new thing
things.Add("Some other thing", new List<int>() {1, 2, 3, 4, 5});
// Try get thing
if (things.TryGetValue("First thing", out var list)) {
// "First thing" exists, list is corresponding value
}
else {
// "First thing" doesn't found
}
// Remove "Some other thing"
things.Remove("Some other thing");
// Iterate over all {Key, Value} pairs (let's print them):
foreach (var pair in things)
Console.WriteLine($"{pair.Key} :: [{string.Join(", ", pair.Value)}]");   

然而,如果Thing不仅仅是SDNA + Name的组合(预计会有更多的属性和方法(,我建议

private Dictionary<string, Thing> things

申报

相关内容

最新更新