我想在我的C#类中初始化一个静态集合 - 如下所示:
public class Foo {
private static readonly ICollection<string> g_collection = ???
}
Run Code Online (Sandbox Code Playgroud)
我不确定这样做的正确方法; 在Java中我可能会做类似的事情:
private static final Collection<String> g_collection = Arrays.asList("A", "B");
Run Code Online (Sandbox Code Playgroud)
在C#2.0中是否有类似的结构?
我知道在C#/ .NET的更高版本中你可以做集合初始化器(http://msdn.microsoft.com/en-us/library/bb384062.aspx),但目前我们的系统不能选择迁移.
澄清我原来的问题 - 我正在寻找一种方法来简洁地声明一个简单的静态集合,例如一个简单的常量字符串集合.对于更复杂的对象的集合,静态初始化器方式也非常好.
谢谢!
Ben*_*ter 27
如果我完全理解你的问题,似乎有些人忽略了这一点,你正在寻找以类似于Java的方式创建静态集合,因为你可以在一行代码中声明和填充而无需创建专用这样做的方法(根据其他一些建议).这可以使用数组文字(写入两行以防止滚动)来完成:
private static readonly ICollection<string> Strings =
new string[] { "Hello", "World" };
Run Code Online (Sandbox Code Playgroud)
这一次都使用项目列表声明和填充新的只读集合.在2.0和3.5中工作,我测试它只是为了倍加肯定.
在3.5中你可以使用类型推断,所以你不再需要使用string []数组来删除更多的击键:
private static readonly ICollection<string> Strings =
new[] { "Hello", "World" };
Run Code Online (Sandbox Code Playgroud)
注意第二行中缺少的"字符串"类型.从数组初始值设定项的内容自动推断字符串.
如果要将其填充为列表,只需为新列表a la更新新字符串[]:
private static readonly ICollection<string> Strings =
new List<string>() { "Hello", "World" };
Run Code Online (Sandbox Code Playgroud)
当然,因为你的类型是IEnumerable而不是特定的实现,如果你想访问特定于List <string>的方法,比如.ForEach(),你需要将它转换为List:
((List<string>)Strings).ForEach(Console.WriteLine);
Run Code Online (Sandbox Code Playgroud)
但这对于可迁移性来说是一个很小的代价[就是这个词?].
静态结构:
public class Foo
{
private static readonly ICollection<string> _collection;
static Foo()
{
_collection = new List<string>();
_collection.Add("One");
_collection.Add("Two");
}
}
Run Code Online (Sandbox Code Playgroud)
但请注意,在这种情况下,您只需初始化内联集合(建议出于性能原因):
private static readonly ICollection<string> _collection = new List<string>(new string[] { "One", "Two" });
Run Code Online (Sandbox Code Playgroud)
这实际上取决于初始化代码的复杂程度.
也许你可以调用静态方法:
public class Foo
{
private static readonly ICollection<string> g_collection = initializeCollection();
private static ICollection<string> initializeCollection()
{
... TODO allocate and return something here ...
}
}
Run Code Online (Sandbox Code Playgroud)
或者,拥有一个静态构造函数(正如其他人建议的那样)可能是等效的,甚至更具惯用性.
| 归档时间: |
|
| 查看次数: |
19210 次 |
| 最近记录: |