1

簡単に言うと、ユーザーデータを保存するために、シリアル化できる辞書のような機能を備えたオブジェクトのセットが必要でした。元のディクショナリは、Itemオブジェクトの配列と、ユーザーが「保持する」各オブジェクトの量を保持するDictionaryクラスでした。インターネットでいくつかの推奨事項を見つけた後、KeyedCollectionから自分の辞書のようなクラスを実装しようとしましたが、オブジェクトを追加できないようです。オブジェクトを間違って追加していますか、それともコレクションに何か問題がありますか?

'SerialDictionary'クラス:

public class SerialDictionary : KeyedCollection<Item, int>
{
    protected override int GetKeyForItem(Item target)
    {
        return target.Key;
    }
}

public class Item
{
    private int index;
    private string attribute;

    public Item(int i, string a)
    {
        index = i;
        attribute = a;
    }

    public int Key
    {
        get { return index; }
        set { index = value; }
    }

    public string Attribute
    {
        get { return attribute; }
        set { attribute = value; }
    }
}

メインフォーム(オブジェクトを追加しようとしている)

public partial class Form1 : Form
{
    SerialDictionary ItemList;
    Item orb;

    public Form1()
    {
        InitializeComponent();
        ItemList = new SerialDictionary();
        orb = new Item(0001, "It wants your lunch!");
        orb.Key = 001;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ItemList.Add(orb);
    }
}

オブジェクトを追加しようとしたときに受け取るエラー:

'System.Collections.ObjectModel.Collection.Add(int)'に最適なオーバーロードされたメソッドの一致には、いくつかの無効な引数があります

そこにintをスローするとコンパイルされますが、そこにItemオブジェクトのコレクションを取得しようとしています...

4

1 に答える 1

1

あなたはそれを後方に持っています、それは次のようになります:

public class SerialDictionary : KeyedCollection<int, Item>

キータイプは最初に署名に含まれ、次にアイテムタイプになります。

于 2012-02-25T02:53:59.583 に答える