我想在编译时填充字符串数组的List
这样的事情:
Listsynonyms = new List { { "enabled", "enable", "enabling" }, { "disabled", "disable", "disabling" }, { "s0", "s0 state" }, { "s5", "s5 state" } };
但我得到一个编译错误:
No overloaded method 'Add' takes 2 arguments
为什么是这样?如果它们不是字符串数组,它就可以工作List
您没有在示例中创建数组,请尝试以下操作:
Listsynonyms = new List { new[] { "enabled", "enable", "enabling" }, new[] { "disabled", "disable", "disabling" }, new[] { "s0", "s0 state" }, new[] { "s5", "s5 state" } };
您需要添加一个字符串数组
Listsynonyms = new List { new string[] { "enabled", "enable", "enabling" }, new string[] { "disabled", "disable", "disabling" }, new string[] { "s0", "s0 state" }, new string[] { "s5", "s5 state" } };
为List
初始化程序创建隐式类型数组:
Listsynonyms = new List { new [] { "enabled", "enable", "enabling" }, new [] { "disabled", "disable", "disabling" }, new [] { "s0", "s0 state" }, new [] { "s5", "s5 state" } };
new [] { ... }
相当于new string[] { ... }
当数组中的对象类型都是时string
.如果数组中对象的类型不同,您将使用隐式语法获得错误.
究其原因,你的代码并没有工作在阐述了如何:初始化字典与集合初始化器(C#编程指南):
字典包含键/值对的集合.它的Add方法有两个参数,一个用于键,一个用于值.要初始化Dictionary 或Add方法采用多个参数的任何集合,请将每组参数括在大括号中...
因此,在语法中
{ { "enabled", "enable", "enabling" }, }
编译器期望您的集合有一个Add(string, string, string)
方法.因为没有这样的方法List
,所以编译失败.
实际上,可以使用这种语法创建这样的集合并对其进行初始化.如果您创建以下集合:
public class TripleCollection: IEnumerable > { readonly List > list = new List >(); public void Add(T first, T second, T third) { list.Add(Tuple.Create(first, second, third)); } public IEnumerator > GetEnumerator() { return list.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } }
以下将成功编译并创建一个包含一个3元组的集合:
var tuples = new TripleCollection{ { "1", "2", "3" }, };
您还可以创建以下List
子类:
public class ListOfArray: List { public new void Add(params T[] args) { base.Add(args); } }
并使用所需的语法初始化它:
var synonyms = new ListOfArray{ { "enabled", "enable", "enabling" }, { "disabled", "disable", "disabling" }, { "s0", "s0 state" }, { "s5", "s5 state" } };
但List
正如其他人所指出的那样,您需要通过显式分配每个string []
条目来初始化您的同义词列表,而不是为每个条目使用隐式集合intializer:
var synonyms = new List{ new [] { "enabled", "enable", "enabling" }, new [] { "disabled", "disable", "disabling" }, new [] { "s0", "s0 state" }, new [] { "s5", "s5 state" } };
您需要指定内部对象是数组,以便它不会查找多参数Add方法.
Listsynonyms = new List { new[] { "enabled", "enable", "enabling" }, new[] { "disabled", "disable", "disabling" }, new[] { "s0", "s0 state" }, new[] { "s5", "s5 state" } };