【问题标题】:Trying to implement Serializble DIctionary from Keyedcollection, unable to add objects尝试从 Keyedcollection 实现 Serializble DIctionary,无法添加对象
【发布时间】:2012-03-14 23:38:01
【问题描述】:

长话短说,我需要一组具有类似字典功能的对象,可以序列化以保存用户数据。原始字典是一个 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 对象的集合...

【问题讨论】:

    标签: c# inheritance collections dictionary keyedcollection


    【解决方案1】:

    你倒过来了,应该是:

    public class SerialDictionary : KeyedCollection<int, Item>
    

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

    【讨论】:

    • 索引是否可能是除 int 以外的任何内容?我最初使用 Item 类作为索引,但如果需要,我可以务实地更改它。
    猜你喜欢
    • 2011-03-10
    • 1970-01-01
    • 2018-09-25
    • 2020-06-11
    • 1970-01-01
    • 2014-12-22
    相关资源
    最近更新 更多