我们如何在 C# 中创建对象列表并通过该对象中的特定字段访问它们?
例如拿这个对象:
class Section
{
public string Name { get; }
public long Size { get; }
public Section(string name, long size)
{
Name = name;
Size = size;
}
}
我想创建一个我可以通过 Section.Name 访问的这些对象的列表。
我可以像这样创建一个字典:
private static readonly Dictionary<string, Section> validSections = new Dictionary<string, Section>
{
{ "section-a", new Section("section-a", 1) },
{ "section-b", new Section("section-b", 2) },
{ "section-c", new Section("section-c", 3) },
{ "section-d", new Section("section-d", 4) },
};
但是如您所见,我必须声明两次节名,这看起来很不雅观。有没有更优雅的方式?
最佳答案
But as you see, I have to declare the section name twice, which looks inelegant. Is there a more elegant way?
为避免重复输入,您可以通过 ToDictionary
调用从部分集合创建字典:
private static readonly Dictionary<string, Section> validSections = new[] {
new Section("section-a", 1),
new Section("section-b", 2),
new Section("section-c", 3),
new Section("section-d", 4)
}.ToDictionary(s => s.Name);
关于c# - 定义对象列表。通过对象中的特定字段获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43227488/