下面的ArrayList可以直接初始化而不需要aFileExt字符串数组吗?
private static string[] aFileExt =
{"css", "gif", "htm", "html", "txt", "xml" };
private System.Collections.ArrayList alFileTypes =
new System.Collections.ArrayList(aFileExt);
以下行是目标,但我的.Net编译器不喜欢它:
private static System.Collections.ArrayList alFileTypes =
new System.Collections.ArrayList({"css","gif","htm","html","txt","xml"});
我使用的是.net Micro Framework,因此无法访问泛型类型。
答案 0 :(得分:67)
C#1或2:
private static ArrayList alFileTypes =
new ArrayList(new string[] {"css","gif","htm","html","txt","xml"});
C#3使用隐式类型数组:
private static ArrayList alFileTypes =
new ArrayList(new[] {"css","gif","htm","html","txt","xml"});
C#3使用集合初始化程序:
private static ArrayList alFileTypes =
new ArrayList{"css","gif","htm","html","txt","xml"};
或者创建自己的帮助方法:
public static ArrayList CreateList(params object[] items)
{
return new ArrayList(items);
}
然后:
static ArrayList alFileTypes = CreateList("css","gif","htm","html","txt","xml");
您没有使用通用集合的原因,顺便说一下?
答案 1 :(得分:13)
如果您使用的是.NET 2.0或更高版本,则应使用通用的List<T>
类型(即使它是List<object>
,它将为您提供与ArrayList
相同的功能)
如果您使用的是.NET 3.5或更高版本,则可以使用以下语法:
private static List<string> fileTypes = new List<string>()
{
"css","gif","htm","html","txt","xml"
};
但是,无论哪种方式,如果你想坚持ArrayList
,你都可以这样做:
private static System.Collections.ArrayList alFileTypes =
new System.Collections.ArrayList(new object[] {"css","gif","htm","html","txt","xml"});
答案 2 :(得分:8)
C#3.0,使用通用List<T>
,而不是ArrayList
:
private static List<string> alFileTypes =
new List<string> {"css","gif","htm","html","txt","xml"};
答案 3 :(得分:1)
private static System.Collections.ArrayList alFileTypes =
new System.Collections.ArrayList(new string [] {"css","gif","htm","html","txt","xml"});
答案 4 :(得分:1)
尝试
private static System.Collections.ArrayList alFileTypes = new System.Collections.ArrayList(){"css","gif","htm","html","txt","xml"};
答案 5 :(得分:0)
是的,只需更改
private static System.Collections.ArrayList alFileTypes =
new System.Collections.ArrayList({"css","gif","htm","html","txt","xml"});
到
private static System.Collections.ArrayList alFileTypes =
new System.Collections.ArrayList(new string[] {"css","gif","htm","html","txt","xml"});