为什么存在这种令人困惑的语法?
Why this confusing syntax exists?
我刚读完 。
如果我们有 属性 字典类型:
public class Test
{
public Dictionary<string, string> Dictionary { get; set; } = new Dictionary<string, string>
{
{"1", "1" },
{"2", "2" },
};
}
然后我们可以构造对象并为其添加值
var test = new Test { Dictionary = { { "3", "3" } } };
Console.WriteLine(test.Dictionary.Count); // 3
而且我不明白为什么存在这样一个令人困惑的语法添加项目?在查看其他人的代码时,很容易将其与 非常相似的
混淆
var test = new Test { Dictionary = new Dictionary<string, string> { { "3", "3" } } };
Console.WriteLine(test.Dictionary.Count); // 1
如果可以进行以下操作,我会更满意(但事实并非如此):
var dictionary = new Dictionary<string, string> { { "1", "1" } };
...
// adding a new value
dictionary = { { "2" , "2"} }; // invalid expression term '{'
那么为什么需要并存在这种添加形式?面试?
集合初始化器语法只是一种使用对象初始化器将集合(包括字典)初始化为复杂对象模型的一部分的简便方法。例如:
var model = new SomeModel {
Name = "abc",
Id = 42,
SpecialMaps = {
{ "foo", "bar" },
{ "magic", "science" },
}
};
如果您不喜欢它:就不要使用它;但与手动 .Add
等效的是 IMO 不那么优雅 - 很多事情都是自动处理的,例如只阅读 属性 一次。实际同时创建集合的较长版本的工作方式非常相似。
请注意,现在还有一个索引器变体:
var model = new SomeModel {
Name = "abc",
Id = 42,
SpecialMaps = {
["foo"] = "bar",
["magic"] ="science",
}
};
这非常相似,但不是使用 collection.Add(args);
,而是使用 collection[key] = value;
。同样,如果它让您感到困惑或冒犯您:请不要使用它。
以这个例子为例,Thing
的构造函数创建一个 Stuff
,Stuff
的构造函数创建 Foo
列表
var thing = new Thing();
thing.Stuff.Foo.Add(1);
thing.Stuff.Foo.Add(2);
thing.Stuff.Foo.Add(3);
现在您可以使用初始化程序将其简化为以下内容。
var thing = new Thing
{
Stuff.Foo = { 1, 2, 3 }
};
您只能对集合使用这种类型的初始化,而不是在嵌套时首先更新集合,因为在这种情况下集合可以存在,但不能直接分配给变量。
最终,当语言设计者看到他们认为可以简化的代码模式时,他们很可能会添加这种语法糖。
我刚读完
如果我们有 属性 字典类型:
public class Test
{
public Dictionary<string, string> Dictionary { get; set; } = new Dictionary<string, string>
{
{"1", "1" },
{"2", "2" },
};
}
然后我们可以构造对象并为其添加值
var test = new Test { Dictionary = { { "3", "3" } } };
Console.WriteLine(test.Dictionary.Count); // 3
而且我不明白为什么存在这样一个令人困惑的语法添加项目?在查看其他人的代码时,很容易将其与 非常相似的
混淆 var test = new Test { Dictionary = new Dictionary<string, string> { { "3", "3" } } };
Console.WriteLine(test.Dictionary.Count); // 1
如果可以进行以下操作,我会更满意(但事实并非如此):
var dictionary = new Dictionary<string, string> { { "1", "1" } };
...
// adding a new value
dictionary = { { "2" , "2"} }; // invalid expression term '{'
那么为什么需要并存在这种添加形式?面试?
集合初始化器语法只是一种使用对象初始化器将集合(包括字典)初始化为复杂对象模型的一部分的简便方法。例如:
var model = new SomeModel {
Name = "abc",
Id = 42,
SpecialMaps = {
{ "foo", "bar" },
{ "magic", "science" },
}
};
如果您不喜欢它:就不要使用它;但与手动 .Add
等效的是 IMO 不那么优雅 - 很多事情都是自动处理的,例如只阅读 属性 一次。实际同时创建集合的较长版本的工作方式非常相似。
请注意,现在还有一个索引器变体:
var model = new SomeModel {
Name = "abc",
Id = 42,
SpecialMaps = {
["foo"] = "bar",
["magic"] ="science",
}
};
这非常相似,但不是使用 collection.Add(args);
,而是使用 collection[key] = value;
。同样,如果它让您感到困惑或冒犯您:请不要使用它。
以这个例子为例,Thing
的构造函数创建一个 Stuff
,Stuff
的构造函数创建 Foo
列表
var thing = new Thing();
thing.Stuff.Foo.Add(1);
thing.Stuff.Foo.Add(2);
thing.Stuff.Foo.Add(3);
现在您可以使用初始化程序将其简化为以下内容。
var thing = new Thing
{
Stuff.Foo = { 1, 2, 3 }
};
您只能对集合使用这种类型的初始化,而不是在嵌套时首先更新集合,因为在这种情况下集合可以存在,但不能直接分配给变量。
最终,当语言设计者看到他们认为可以简化的代码模式时,他们很可能会添加这种语法糖。