public class rectangular//自定义矩形类
    {
        public int len, width,circle;
        public rectangular()
        {
            this.len = 0;
            this.width = 0;
            this.circle = 0;
        }
        public rectangular(int _len, int _width)
        {
            this.len = _len;
            this.width =_width;
            this .circle =2*(this.len +this.width );
        }
    }    class Program
    {
       // 编写一个矩形类,私有数据成员为举行的长(len)和宽(wid),
       // 无参构造函数将len和wid设置为0,有参构造函数设置和的值,
       // 另外,类还包括矩形的周长、求面积、取矩形的长度、取矩形的宽度、
       // 修改矩形的长度和宽度为对应的形参值等公用方法。        static void Main(string[] args)
        {
            int paramLen, paramWidth;
            
            Console.WriteLine("请输入矩形的长:");
            string temp=Console.ReadLine();
            bool flag=int.TryParse(temp, out paramLen);
            while (!flag)
            {
                Console.WriteLine("请重新输入矩形的长:");
                temp = Console.ReadLine();
                flag = int.TryParse(temp, out paramLen);
            
            }            Console.WriteLine("请输入矩形的宽:");
            temp=Console.ReadLine();
            flag=int.TryParse(temp, out paramWidth);
            while (!flag)
            {
                Console.WriteLine("请重新输入矩形的宽:");
                temp = Console.ReadLine();
                flag = int.TryParse(temp, out paramWidth);
            }
           
            rectangular myRectangular = new rectangular(paramLen ,paramWidth );
            int s = myRectangular.len * myRectangular.width;
            Console.WriteLine("矩形面积:{0}",s.ToString ());
        }
    }
总觉得自己写的代码看起来就傻傻的,模块化不够。以上代码是不是可以写的更聪明些?先谢谢了!

解决方案 »

  1.   

    public int len, width,circle; 
    -----------------------------
    这些都应该封装为属性,circle其实没必要了,可以计算得出的。
      

  2.   

    1. 赋值部分可以优化一下:
            static int GetValue(string strInfor)
            {
                int param = 0;
                string temp = string.Empty;
                do
                {
                    Console.WriteLine(strInfor);
                    temp = Console.ReadLine();
                } while (!int.TryParse(temp, out param));
                return param;
            }
    调用:  paramLen = GetValue("请输入矩形的长:");
           paramWidth = GetValue("请输入矩形的宽:");2. 似乎应该在rectangular中计算矩形的面积.
      

  3.   

    circle作为一个方法的返回值即可。
    这东西蛮考验面向对象思想的,类似于工业设计制造对仿生学的利用一样。