C#: Custom 2-dim arrays trouble
I'm trying to create a two-dimensional array of my custom class Cell
with the following code:
public class Cell
{
int top;
int bottom;
}
public Form1()
{
Cell[,] elements;
elements = new Cell[10,10];
Random r = new Random();
for (int i=0; i!=10; i++)
{
for (int j=0; j!=10; j++)
{
elements[i,j].top = r.Next();
}
}
}
But I always receive the following error: Inconsistent accessibility: ... and something about 开发者_运维知识库'Cell is less accesible'...
How do I correctly define a two-dimensional array of a custom class?
I suspect you haven't actually got quite that code. I suspect you've left the "public" off the declaration of Cell
in your real code, and that you've got a public method which uses it somewhere in the signature. Something like this:
class Cell { ... }
public class Foo
{
public Cell[,] DoStuff()
{
}
}
Alternatively, it's possible that you've got Cell
as a public class but nested within a non-nested class.
I don't think it's really got anything to do with arrays.
However, it would be a lot clearer if you'd post the full error message instead of "and something to do with"... It would also help if you'd post a short but complete program demonstrating the problem.
EDIT: As others have pointed out, the code you posted wouldn't compile, but for a different reason. I doubt that you made up an error message about inconsistent accessibility, so I strongly suspect the code you've posted isn't actually like your real code at all - at least in terms of accessibility.
Again, without seeing real code, it's very hard to give an accurate answer.
The default accessibility for an attribute is private. Try this:
public class Cell
{
public int top;
public int bottom;
}
Better still, make them auto-properties:
public class Cell
{
public int top { get; set; }
public int bottom { get; set; }
}
The accessibility error is not related to the array creating. The most common scenerio for that error is a public method with a parameter that is of a private or internal type.
I suggest you make properties out of top
and bottom
fields. These have a private
access hence the error:
public class Cell
{
public int top { get; set; };
public int bottom { get; set; };
}
精彩评论