c# - Getting Value from dictionary, when the key in an object -
i have object pixeldata:
public class pixeldata { public int x {get;set;} public int y {get;set;} }
pixel data key dictionary.
dictionary<pixeldata, int> dict
how use pixel data right way?
a simple solution use struct instead of class pixeldata
:
public struct pixeldata { public int x; public int y; } var dict = new dictionary<pixeldata, int>();
you can read differences between structs , classes in c# here. short version: structs value types, unlike classes reference types. therefore, if want retrieve value dictionary, don't need reference original pixeldata
instance used key. can go ahead , create new instance, exact same x
, y
used key, , work fine.
// add new value dictionary new pixeldata instance key dict.add(new pixeldata { x = 1, y = 1 }, 42); // retrieving value using new, identical instance of pixeldata works fine int value = dict[new pixeldata { x = 1, y = 1 }]);
Comments
Post a Comment