用常量字面值初始化ArrayList
下面的ArrayList可以直接初始化而不需要aFileExtstring数组吗?
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,因此无法访问genericstypes。
C#1或2:
private static ArrayList alFileTypes = new ArrayList(new string[] {"css","gif","htm","html","txt","xml"});
使用隐式types数组的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"};
或者创build你自己的帮手方法:
public static ArrayList CreateList(params object[] items) { return new ArrayList(items); }
然后:
static ArrayList alFileTypes = CreateList("css","gif","htm","html","txt","xml");
任何你不使用generics集合的原因,顺便说一句?
如果您使用的是.NET 2.0或更高版本,那么应该使用通用的List<T>
types(即使它是List<object>
,这会为您提供与ArrayList
相同的function)。
如果您使用.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"});
C#3.0与通用List<T>
,而不是一个ArrayList
:
private static List<string> alFileTypes = new List<string> {"css","gif","htm","html","txt","xml"};
private static System.Collections.ArrayList alFileTypes = new System.Collections.ArrayList(new string [] {"css","gif","htm","html","txt","xml"});
尝试
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({"css","gif","htm","html","txt","xml"});
至
private static System.Collections.ArrayList alFileTypes = new System.Collections.ArrayList(new string[] {"css","gif","htm","html","txt","xml"});