用C#在结构中定义Dictionary



我有Struct

    struct User
    {
        public int id;
        public Dictionary<int, double> neg;         
    }
    List<User> TempUsers=new List<users>();
    List<User> users = new List<User>();

我的问题是,当我运行这个代码时

TempUsers=users.ToList();
TempUsers[1].neg.Remove(16);

用户中的neg字典也可以删除值为16的密钥

这是因为Dictionary是一个引用类型。你应该克隆它,例如:
class User : IClonable
{
    public int Id { get; set; }
    public Dictionary<int, double> Neg { get; set; }
    public object Clone()
    {
        // define a new instance
        var user = new User();
        // copy the properties..
        user.Id = this.Id;    
        user.Neg = this.Neg.ToDictionary(k => k.Key,
                                         v => v.Value);
        return user;
    }
}

您不应该在这样的类型中使用struct。在这个链接中,有一个关于何时以及如何使用结构的很好的解释。

Dictionary是一种引用类型。你应该克隆你的字典:这是一个例子:

    struct User : ICloneable
{
    public int id;
    public Dictionary<int, double> neg;
    public object Clone()
    {
        var user = new User { neg = new Dictionary<int, double>(neg), id = id };
        return user;
    }
}

最新更新