首页 > 解决方案 > 将类设为私有,因此值不会被修改

问题描述

我希望将 tile 类设为私有;特别是它不应该能够在构建后更改图块的值。

using System;
using System.Collections.Generic;
using System.Text;

namespace Tiles
{
    class tile
    {
         readonly int[,] arr;//added this 
         public int [,] Print2DArray(int n)
        {
            int[,] arr;
            do
            {
                Random random = new Random();
                arr= new int[n, n];
                int k = 0;
                for (int i = 0; i < n; i++)
                {
                    for (int j = 0; j < n; j++)
                    {
                        arr[i, j] = k++;
                    }
                }

returns对于主程序,磁贴和主程序是单独的 .cs 文件我将如何制作它,以便返回后的值不会被修改。

主要的:

Tile mytiles = new Tile();
int[,] original = mytiles.Print2DArray(n);

标签: c#arrays

解决方案


要使值无法重新定义,请使用const

您的 tile 类应该 1) 以大写字母开头 2) 具有适当的构造函数 3) 具有只有 getter 的属性,或者readonly如果您希望 Tile 类是不可变的(不是私有的)


推荐阅读