c# 如何最好地将数组或列表放入也有名称的 class 中?
c# how to best put array or list into class that also has name?
我尝试做人们认为最好的事情,而不是按照我以前的非 OOP 方式去做。我需要存储大约 9 个不同长度的 Int 数组。我还需要将它们与字符串名称“this is called etc.”相关联。我认为将它们全部存储到 class 对象中是有意义的,这样我以后就可以干净利落地遍历它们而无需查看两个不同的地方使用相同的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"}
}
我得到一个空引用异常(我假设它的原因是列表在 class 中)我尝试以这种方式创建一个列表来清除空引用,但它有一些其他错误。
List<Thing> things = new List<Thing>();
things.Add(new Thing() {SDNA = {2,4,5,7,9,11},Name = "The first things name"});
无效令牌等错误。我是否应该只使用两个不同的存储数组,一个用于名称,一个锯齿状数组用于 Int,然后分别引用它们?这让我觉得很丑。为什么我不能将它们全部存储到一个东西中?
谢谢!
在最简单的情况下如果您只想拥有名称到值(数组)关联,您可以尝试使用简单的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
声明
我尝试做人们认为最好的事情,而不是按照我以前的非 OOP 方式去做。我需要存储大约 9 个不同长度的 Int 数组。我还需要将它们与字符串名称“this is called etc.”相关联。我认为将它们全部存储到 class 对象中是有意义的,这样我以后就可以干净利落地遍历它们而无需查看两个不同的地方使用相同的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"}
}
我得到一个空引用异常(我假设它的原因是列表在 class 中)我尝试以这种方式创建一个列表来清除空引用,但它有一些其他错误。
List<Thing> things = new List<Thing>();
things.Add(new Thing() {SDNA = {2,4,5,7,9,11},Name = "The first things name"});
无效令牌等错误。我是否应该只使用两个不同的存储数组,一个用于名称,一个锯齿状数组用于 Int,然后分别引用它们?这让我觉得很丑。为什么我不能将它们全部存储到一个东西中?
谢谢!
在最简单的情况下如果您只想拥有名称到值(数组)关联,您可以尝试使用简单的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
声明