正在尝试从Keyedcollection实现Serializable DIctionary,无法添加对象

本文关键字:DIctionary 对象 添加 Serializable 实现 Keyedcollection | 更新日期: 2023-09-27 18:25:36

长话短说,为了保存用户数据,我需要一组具有类似字典功能的对象。原始字典是一个dictionary类,它包含Item对象的数组以及用户"持有"的每个对象的数量。在互联网上找到一些推荐后,我尝试从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对象的集合。。。

正在尝试从Keyedcollection实现Serializable DIctionary,无法添加对象

如果你把它倒过来,它应该是:

public class SerialDictionary : KeyedCollection<int, Item>

密钥类型首先出现在签名中,然后是项类型。