C# 使用常量文本初始化ArrayList
下面的ArrayList是否可以在不需要FileExt字符串数组的情况下直接初始化C# 使用常量文本初始化ArrayList,c#,.net,.net-micro-framework,C#,.net,.net Micro Framework,下面的ArrayList是否可以在不需要FileExt字符串数组的情况下直接初始化 private static string[] aFileExt = {"css", "gif", "htm", "html", "txt", "xml" }; private System.Collections.ArrayList alFileTypes = new System.Collections.ArrayList(aFileExt); 下面这行是目标,但我的.Net编译器不喜
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,因此无法访问泛型类型。是的,只需更改即可
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"});
到
C#1或2:
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);
}
然后:
顺便说一句,您不使用泛型集合的任何原因?如果您使用的是.NET 2.0或更高版本,您应该使用泛型
列表
类型(即使它是列表
,这将为您提供与ArrayList
相同的功能)
如果您使用的是.NET 3.5或更高版本,则可以使用以下语法:
private static List<string> fileTypes = new List<string>()
{
"css","gif","htm","html","txt","xml"
};
试一试
C#3.0具有通用的列表
,而不是数组列表
:
private static List<string> alFileTypes =
new List<string> {"css","gif","htm","html","txt","xml"};
私有静态列表文件类型=
新列表{“css”、“gif”、“htm”、“html”、“txt”、“xml”};
+1,用于使用List或ArrayList(并且仍然回答原始问题)。实际上,我的.Net泛型版本不受支持。感谢您的帮助。是的,泛型和许多系统.net集合在我的.net版本中不受支持。@MandoMando:对于这样的问题,可能需要说明您使用的是.net的哪个版本,以及C#的哪个版本。C#3集合初始值设定项是我的解决方案,因为:1。它在我的.NET2(特殊)版本上编译。不创建新对象。(本例中内存是一个问题)Jon,我并没有故意提到我的.net版本,因为它正处于测试阶段并在不断变化,而且世界上很少有人使用netmf v4.0。@MandoMando:这仍然是有用的信息。例如,如果你知道即使没有泛型也可以使用C#3特性,那就告诉我们集合初始值设定项将是一个很好的方法。我认为这也很聪明。在我看来,它甚至不像是要编译:)谢谢!杰出的但要编译,LHS需要是List类型:private static List alFileTypes=new List{“css”,…
@Rubistro,的确……我忘了替换“ArrayList”;)
static ArrayList alFileTypes = CreateList("css","gif","htm","html","txt","xml");
private static List<string> fileTypes = new List<string>()
{
"css","gif","htm","html","txt","xml"
};
private static System.Collections.ArrayList alFileTypes =
new System.Collections.ArrayList(new object[] {"css","gif","htm","html","txt","xml"});
private static System.Collections.ArrayList alFileTypes = new System.Collections.ArrayList(){"css","gif","htm","html","txt","xml"};
private static List<string> alFileTypes =
new List<string> {"css","gif","htm","html","txt","xml"};