readonly和private方法的问题

Rya*_*yan 0 c# constructor readonly

"创建一个名为"DemoSquare"的程序,它启动一个10个Square对象的数组,其边长值为1-10,并显示每个方块的值.Square类包含区域和边长的字段,以及一个构造函数,需要一个区域的参数和一个边的长度.构造函数将其参数分配给Square的长度并调用一个计算区域字段的私有方法.还包括只读属性以获得Squares方面和地区."

现在我认为这是一个技巧问题,因为我无法获得私有方法来计算区域,因为只读赋值,但这是我的代码:

    class demoSquares
    {

        static void Main(string[] args)
        {
            Square[] squares = new Square[10];//Declares the array of the object type squares
            for (int i = 0; i < 10; i++)
            {
                //Console.WriteLine("Enter the length");
                //double temp = Convert.ToDouble(Console.ReadLine());
                squares[i] = new Square(i+1);//Initializes the objects in the array 
            }

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(squares[i]);
            }//end for loop, prints the squares
        }//end main

      }//end class
Run Code Online (Sandbox Code Playgroud)

这是Square Class:

   public class Square
   {

    readonly double length;
    readonly double area;

    public Square(double lengths)//Constructor 
    {
       length = lengths;
       area = computeArea();
    }

    private double computeArea()//getmethod 
    {
        double areaCalc = length * length;
        return areaCalc;
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

不要将只读属性与只读字段混淆.

   public class Square
   {
        public Square(double lengths)
        {
           Length = lengths;
           Area = computeArea();
        }

        //Read only property for Length (privately settable)
        public double Length {get; private set;}

        //Read only property for Area (privately settable)
        public double Area {get; private set;}

        //Private method to compute area.
        private double ComputeArea()
        {
            return Length * Length;
        }
    }
Run Code Online (Sandbox Code Playgroud)