简体   繁体   中英

Define Dictionary in struct with C#

I have Struct

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

my Problem is, when I run this code

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

neg dictionary in users aslo remove key with value=16

That is because the Dictionary is a reference type. You should clone it, for sample:

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;
    }
}

You shouldn't use a struct in a type like this. In this link, there is a good explanation about when and how you should use a struct.

Dictionary is a reference type. You should clone you dictionary: this is an example:

    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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM