开发者

Strange C# struct in collection behaviour

开发者 https://www.devze.com 2023-01-07 14:46 出处:网络
Any ideas as to why this public Collection<Point> data = new Collection<Point>(){ new Point{X=10,Y=20},

Any ideas as to why this

    public Collection<Point> data = new Collection<Point>(){
            new Point{X=10,Y=20},
            new Point{X=20,Y=30},
            new Point{X=40,Y=20},
            new Point{X=10,Y=20}
           };

(notice the identical first and last elements) gives the error

An item with the same key has already been added.

If you change the last element to Y=20.1 or anything that makes it different then it works. Also you can add the elements anyway you like and get the same result.

The problem is obviously开发者_如何学Python due to Point being a value type because it goes away if you define and use a point class and I know that there are problems with using structs in other collection types but this has to do with the difference between value and ref return types. What mystifies me is that this works if the all the structs have different field values.


The reason is because equality of a value type is based on its values - for struct it is equality across all its fields.

Reference type equality is based on the reference itself and thus works. Changing the struct values to be all different also works.

If you just want a list of stuff, just use List<Point>, I think that will accept duplicates.

Update: it looks like your collection class is detecting duplicate entries and you are trying to add duplicates. If you want to add duplicates, I would say you cannot use this class.


Have you tried using a List instead? I think it should work!

Hope that helps!


I'm not familiar with this collection class you're using but apparently it doesn't allow multiple items to be in it. As it is with a SET collection. So I guess the Collection you're using is equivalent to:

Dictionary<String, Point>

but since you you dont have a key it's more like

HashSet<Point>

Just like your collection class a HashSet requires all keys to be unique. Like Kieren mentions a List would be more suitable for you. A list allows multiple entries to be the same.

Indeed if Point was a class it would allow duplicates since Objec1 != Object2 to even if their values are the same.


I'm really not sure on this, but I have a feeling that because the compiler generates a strong Collections item that doesn't require to box/unbox value types, the key check is done on the explicit value type itself, which produces the duplicate key exception?

That's really just a shot in the dark!


What is Collection class. It's not .NET Framework library class. Look docs or sources of this class, it would explain the problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号