如何在以下程序中使用readonly修饰符? [英] How to use readonly modifier in the following program?

查看:61
本文介绍了如何在以下程序中使用readonly修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是Illustrated C#2012一书中的示例。有人可以帮助我并让我理解,我该怎么做才能实现班级的三角形或矩形或圆形部分并找出该区域?



The code below is the example from the book "Illustrated C#2012." Can someone help me and make me understand, what should I do to implement triangle or rectangle or circle portion of the class and find out the area?

{
       class Shape
{
  // Keyword Initialized
   // ↓↓
  readonly double PI = 3.1416;
  readonly int NumberOfSides;
  // ↑↑

  // Keyword Not initialized
  public Shape(double side1, double side2) // Constructor
  {
     // Shape is a rectangle
    NumberOfSides = 4;
    //
    // ... Set in constructor
  }
    public Shape(double side1, double side2, double side3) // Constructor
  {
     // Shape is a triangle
     NumberOfSides = 3;
    //
    // ... Set in constructor
   }
   }





到目前为止,我只能这样做:

{public static void Main()

{

var s = new Shape(1.0,1.2);

Console.WriteLine(s.NumberOfsides);

}



So far I was only able to do:
{public static void Main()
{
var s = new Shape(1.0,1.2);
Console.WriteLine(s.NumberOfsides);
}

推荐答案

有很多方法可以做到这一点,

a更好的方法是将这个Shape作为一个抽象方法,如区域,并将其留给特定的形状来实现实际的区域公式。

但是要坚持你的简单例子,试试这个:

There are a number of ways to do this,
a better way would be to make this Shape an abstract class with abstract method like area and leave it to the specific shape to implement the actual area formula.
But to stick to your simple example, try this:
using System;

public class Program
{
    class Shape
    {
        readonly double PI = 3.1416;
        readonly int NumberOfSides;

        // add a double member
        private double area;

        public Shape(double side1, double side2) // Constructor
        {
            // Shape is a rectangle
            NumberOfSides = 4;

            // calculate the area
            area = side1 * side2;
        }

        // add an accessor method
        public double GetArea()
        {
            return area;
        }
    }

    public static void Main()
    {
        // instantiate a rectangle object
        Shape rectangle = new Shape(10, 20);

        // get the area from the GetArea() method
        Console.WriteLine(rectangle.GetArea());
    }
}


这篇关于如何在以下程序中使用readonly修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆