質問者
Visual C#でクラスのプロパティ作成時に、データ型が配列の場合の例を教えてください

質問
すべての返信
-
インデクサなら書けますけど、同じクラス内に複数そのような定義を作るのはできないのでは?と思っています。
private int[,] _cells = new int[2, 5]; public int this[int x, int y] { get { return _cells[x, y]; } set { _cells[x, y] = value; } }
もし、そういう使い方をしたい場合はクラスを作る方がいいと思いますけどね。
public partial class Form1 : Form { private readonly Cells _cells1 =new Cells(); private readonly Cells _cells2 = new Cells(); public Cells Cells1 { get { return _cells1; } } public Cells Cells2 { get { return _cells2; } } } public class Cells { private readonly int[,] _cells = new int[2, 5]; public int this[int x, int y] { get { return _cells[x, y]; } set { _cells[x, y] = value; } } }
-
getやsetの内容が、この宣言の変数に限らない、配列変数、以下m_Cells->これもあらかじめ、Cellで宣言して、newしてます。
以下のようでも、エラーは出ないのですが、setできないようです。
class ReverseGrid
{
public int CellSize = 48;
public int XCount = 8;
public int YCount = 8;
public int Str_width = 15;
public int[,] Data = new int[8,8];
public Cell[,] m_Cells = new Cell[8, 8];
//public Cell[,] _value = new Cell[8,8];
//public int X;
//public int Y;
public ReverseGrid()
{
for (int i = 0; i <= XCount-1; i++) { for (int j = 0; j <= YCount-1; j++) {
m_Cells[i, j] = new Cell(this, new Point(i, j)); } }
}
public Cell[,] Cells = new Cell[8, 8];
public Cell this[int x, int y]
{
get { return m_Cells[x, y]; }
set{ m_Cells[x, y] = value; }
} -
言葉は正しく、適切にお願いします。
「エラーマークされました」と言われても伝わらないです。二度目ですのでもう少し踏み込んで書きます。
・エラー、あるいは例外を起こした利用側のコードも具体的に記載してください。
・そのコードでどうなることを期待していたのかを具体的に明らかにしてください。
・結果としてどうなったか、エラーなのか、例外なのか、あるいは現象なのかを明確にしてください。
・エラーや例外であれば、その文言を正確に書き写してください。
・現象なのであれば、観測方法も含めて具体的に明らかにしてください。これらを実施してもらえない場合は、現状の反応だと推測困難なので、解決不可能に見えます。
-
インデントやなんやら、ツッコミどころがいっぱい。
m_Cells と Cells というフィールド変数があります。これ、どっちかだけでいいんじゃないですかね?
XCount, YCount って、Data や Cell の数と関連があるのでしょうか?関連があるなら、変えることができたら、特に外部から変更されるのはまずいのではないでしょうか。
それを言ったら、Cells などすべて public なので、変更し放題ですが。class ReverseGrid { public int CellSize = 48; public int XCount = 8; public int YCount = 8; public int Str_width = 15; public int[,] Data = new int[8,8]; public Cell[,] m_Cells = new Cell[8, 8]; public ReverseGrid() { for (int i = 0; i <= XCount-1; i++) { for (int j = 0; j <= YCount-1; j++) { m_Cells[i, j] = new Cell(this, new Point(i, j)); } } } public Cell[,] Cells = new Cell[8, 8]; public Cell this[int x, int y] { get { return m_Cells[x, y]; } set{ m_Cells[x, y] = value; } } }
Jitta@わんくま同盟