web-dev-qa-db-ja.com

定数リテラルでArrayListを初期化する

FileExt文字列配列を必要とせずに、以下のArrayListを直接初期化できますか?

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を使用しているため、ジェネリック型にアクセスできません。

40
MandoMando

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");

ところで、ジェネリックコレクションを使用していない理由は何ですか?

67
Jon Skeet

.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"});
13
Adam Robinson

ArrayListではなく、汎用のList<T>を含むC#3.0:

private static List<string> alFileTypes =
    new List<string> {"css","gif","htm","html","txt","xml"};
8
Thomas Levesque

試してみる

private static System.Collections.ArrayList alFileTypes =   new System.Collections.ArrayList(){"css","gif","htm","html","txt","xml"};
1
TLiebe
private static System.Collections.ArrayList alFileTypes = 
 new System.Collections.ArrayList(new string [] {"css","gif","htm","html","txt","xml"});
1
Sean Bright

はい、変更するだけです

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"});
0
kemiller2002