C#のジェネリック
C++テンプレートの
map<int , map< int , float > > a;
a[1][1] = 10.0f;
float val = a[1][1];
のような事をC#のジェネリックで実現することは可能でしょうか?
Dictionary<int, Dictionary<int, float> > b = new Dictionary<int, Dictionary<int, float> >();
b[1][1] = 10.0f;
とするとKeyNotExceptionがでます。
Dictionary<int, Dictionary<int, float> > b = new Dictionary<int, Dictionary<int, float> >();
b[1] = new Dictionary<int, float>();
b[1][1] = 10.0f;
float val = b[1][1];
とすればできましたが第1キーが異なれば毎回newする必要があります。
キーをペアにする方法も試しました。
public struct Pair{
int x;
int y;
Pair(int _x, int _y) { x = _x; y = _y; }
}
Dictionary<Pair, float> c = new Dictionary<Pair, float>();
c[new Pair(1, 1)] = 10.0f;
float val = c[new Pair(1, 1)];
しかしこれも無駄が多い気がします・・・
自分なりにいろいろ試してみましたが他にスマートな方法、
あるいは意見があればお願い致します。
お礼
なるほど、継承を使えばいいわけですね! ここまでのことは自分では思い浮かばなかったと思います。 ありがとうございました!!