C#中的属性与方法

时间:2017-02-25 17:33:38

标签: c# methods properties

我在一个类中定义了一个变量,让我们说A类:

private char[,] matrix;

稍后在我的代码中,根据某些条件初始化并填充此矩阵。

现在来自另一个不同的班级,让我们说B级,我需要得到最终的矩阵。

所以我有两个选择:

  1. 在A类中实现将从B类访问的公共属性:

    public char[,] GetMatrix 
    { 
      get 
      { 
         if (this.matrix == null || this.matrix.Length == 0)
         {
            // Matrix is null or it has no elements on it.
            return null;
         }
         else
         {
            return this.matrix;
         }
      }
    }
    
  2. 在A类中实现一个将从B类访问的公共方法:

       public char[,] GetMatrix() 
        {  
             if (this.matrix == null || this.matrix.Length == 0)
             {
                // Matrix is null or it has no elements on it.
                return null;
             }
             else
             {
                return this.matrix;
             }
        }
    
  3. 如上所述here,建议在操作返回数组的情况下使用方法。

    也有人说:

      

    使用操作返回数组的方法,因为要保留内部数组,您必须返回数组的深层副本,而不是对属性使用的数组的引用。这一事实,加上开发人员使用属性就好像它们是字段一样,可能导致代码效率非常低

    所以在我的情况下,哪个选项最好?为什么?

0 个答案:

没有答案