简体   繁体   English

C#类中的公共变量

[英]C# Public variables in a class

I have a class which has a 2D jagged array declared in it's constructor, and in that class I have two methods called GetXY and SetXY, that modify said array. 我有一个类,该类的构造函数中声明了一个2D锯齿状数组,在该类中,我有两个方法GetXY和SetXY,它们可以修改所述数组。

However, I am unsure whether I should use these methods or in fact declare the grid as public, meaning there would be 2 ways of setting and reading values in the array, like this: 但是,我不确定我应该使用这些方法还是实际上将网格声明为公共网格,这意味着将有两种设置和读取数组中值的方式,如下所示:

    ProceduralGrid pg = new ProceduralGrid(10, 10);

    pg.grid[0][0] = 2;
    pg.SetXY(0, 0, 2);

Which one shall I use, and why? 我应该使用哪一个?为什么?

Why not use 为什么不使用

    public T this[int x, int y]
    {
        get
        {
            return grid[x][y];
        }
        set
        {
            grid[x][y] = value;
        }
    }

Naturally check for valid x and y etc... 自然检查有效的x和y等...

Use methods to access the array. 使用方法访问数组。 Either SetXY or an indexer as suggested be Alessandro. SetXY或建议的索引器为Alessandro。 That way, you can later change the implementation without changing your class interface. 这样,您以后就可以更改实现,而无需更改类接口。

It is best to use methods to set variables that are used inernally. 最好使用方法来设置内部使用的变量。

This way you can protect your inner object and are free to implement extra validation or modify the object as required. 这样,您可以保护内部对象,并可以自由地进行额外的验证或根据需要修改对象。

This allows you to easily change the behaviour of that object later on. 这使您以后可以轻松更改该对象的行为。

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

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