简体   繁体   English

C# 属性、构造函数、

[英]C# properties, constructor,

I want to create class that draws a board.我想创建绘制板的类。 I wrote code like this (it works):我写了这样的代码(有效):

{
public class Map
{
    public int rows { get; set; }
    public int cols { get; set; }
    public int[,] grid { get; set; }

    public Map(int rows, int cols)
    {
        this.rows = rows;
        this.cols = cols;
        this.grid = new int[rows, cols];
    }
    public void printBoard()
    {
        for (int r = 0; r < rows; r++)
        {
            for (int c = 0; c < cols; c++)

            {
                Console.Write(grid[r, c] + "");
            }
            Console.WriteLine();
        }
    }
}
//Program.cs: 
Map map = new Map(2, 2); map.printBoard();

Questions i have: 1.Can I create array as property and then initialize it(idk how to call it) in constructor as in the code above?我有问题: 1.我可以创建数组作为属性,然后像上面的代码一样在构造函数中初始化它(idk如何调用它)? I read here that i shoud't do it but maby that was not the case https://stackoverflow.com/a/18428679 2. If it's ok, is it good practice to write code like this, maby I coud write it better?我在这里读到我不应该这样做,但也许事实并非如此https://stackoverflow.com/a/18428679 2. 如果没问题,写这样的代码是不是很好的做法,也许我可以写得更好?

As described in the answer you link to, properties should not normally return arrays, because that exposes the internals of a class to the outside, without the control over what is part of the array.正如您链接到的答案中所述,属性通常不应返回数组,因为这会将类的内部结构暴露给外部,而无法控制数组的一部分。 The way you have declared your property, a client can insert arbitrary values into the array and your class has no way of performing any validation.您声明属性的方式,客户端可以将任意值插入数组,而您的类无法执行任何验证。

By convention, properties should use capital names as well.按照惯例,属性也应该使用大写名称。 But in your case, the right thing to do is make all your properties fields and make them private.但就您而言,正确的做法是将所有属性字段设为私有。 Then add an indexer to update the array (Note that it is even possible to change rows and cols from outside, which will most certainly result in undefined behavior).然后添加一个索引器来更新数组(请注意,甚至可以从外部更改rowscols ,这肯定会导致未定义的行为)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM