2

私は、ユーザーが好きなだけ画像を開くことができる一種の画像処理プログラムを書いています。ユーザーが画像を開くたびに、プログラムはオブジェクトを作成する必要があります。これは、クラス MyClass によって定義されます。明らかに、「画像を開く」メソッド内でこのオブジェクトを作成すると (たとえば、メニュー ボタンの [ファイル] -> [開く...] をクリック)、オブジェクトはこのメソッド内でのみ認識され、UI の他のメソッドでは役に立ちません。UI クラス内に配列を作成し、オブジェクトを MyClass[i] に割り当てて i を数え続けることもできますが、ユーザーが開きたい画像の数がわからないため、これはオプションではありません。また、ユーザーは画像を再び閉じることができる必要があります。つまり、このインデックス i は役に立たなくなります。

オブジェクトを動的に追加および削除できるオブジェクトのコレクションをどうにかして持つ方法はありますか? オブジェクトは、たとえばファイル名によって、このコレクション内で自分自身を識別できる必要があります。

私はC#にかなり慣れていないので、すべてをできるだけ詳しく説明してください。

4

2 に答える 2

1

オブジェクトを に格納できますDictionary<TKey,TValue>。この場合、おそらくDictionary<string, MyClass>.

これにより、ファイル名などのキーに基づいてアイテムを検索して保持できます。

于 2012-06-28T23:18:19.940 に答える
1

必要なのは、リストのような動的データ構造です。

ジェネリック (つまりリスト) または非ジェネリック (つまりリスト) バージョンのいずれかを使用できます。リストを使用すると、アイテムを動的に追加または挿入したり、インデックスを決定したり、必要に応じてアイテムを削除したりできます。

リスト操作を使用していると、リストのサイズは動的に拡大/縮小します。

画像が Image 型のオブジェクトとして表されていると仮定すると、次のような List を使用できます。

// instantiation of an empty list
List<Image> list = new List<Image>();

// create ten images and add them to the list (append at the end of the list at each iteration)
for (int i = 0; i <= 9; i++) {

    Image img = new Image();
    list.Add(img);
}

// remove every second image from the list starting at the beginning
for (int i = 0; i <= 9; i += 2) {

    list.RemoveAt(i);
}

// insert a new image at the first position in the list
Image img1 = new Image();
list.Insert(0, img1);

// insert a new image at the first position in the list
IMage img2 = new Image();
list.Insert(0, img2);

辞書を使用した代替アプローチ:

Dictionary<string, Image> dict = new Dictionary<string, Image>();

for (int i = 0; i <= 9; i++) {

    Image img = new Image();

    // suppose img.Name is an unique identifier then it is used as the images keys
    // in this dictionary. You create a direct unique mapping between the images name
    // and the image itself.
    dict.Add(img.Name, img);
}

// that's how you would use the unique image identifier to refer to an image
Image img1 = dict["Image1"];
Image img2 = dict["Image2"];
Image img3 = dict["Image3"];
于 2012-06-28T23:19:10.020 に答える