并非所有函数都必须实例化?

时间:2015-04-28 16:33:10

标签: c#

using System;
namespace RectangleApplication
{
    class Rectangle
    {
        // member variables
        double length;
        double width;
        public void Acceptdetails()
        {
            length = 4.5;
            width = 3.5;
        }

        public double GetArea()
        {
            return length * width;
        }

        public void Display()
        {
            Console.WriteLine("Length: {0}", length);
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Area: {0}", GetArea());
        }
    }

    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.Acceptdetails();
            r.Display();
            Console.ReadLine();
        }
    }
}

运行此C#代码时,结果为:

长度:4.5 宽度:3.5 面积:15.75

我的新手问题是:

如果删除r.Acceptdetails();r.Display();,则它们不会实例化,输出也不符合预期。

那么,为什么不必实例化GetArea()r.GetArea)。

作为一个新手,我试图理解为什么某些功能必须被实例化而其他功能不被实例化。

2 个答案:

答案 0 :(得分:1)

首先,你在第一个地方错了。您没有实例化函数,您实例化类对象。在您的代码中,唯一的实例是Rectangle; r.Acceptdetails(); r.Display(); 级的。{需要时,该函数称为

因此,在您的代码中,您自己调用了两个(实例)函数。

Display()

但是在Console.WriteLine("Area: {0}", GetArea()); 函数中调用了另一个函数;在代码本身。

GetArea()

从这一行可以清楚地看到调用函数public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); } // inside the Main function Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); r.GetArea() Console.ReadLine(); ...只是不在main函数中,而是在另一个函数中。如果您想自己调用该函数,可以将代码更改为

// pass the parameters
public Rectangle(double length, double width) {
    // fill the values
    this.length = length;
    this.width = width;
}

替代代码

同样如前所述,您也可以在构造函数中使用参数。所以你的构造函数可以是这样的......

Acceptdetails()

保留其余功能(但删除不必要的using System; namespace RectangleApplication { class Rectangle { // member variables double length; double width; public Rectangle(double length, double width) { this.length = length; this.width = width; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); } } class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Display(); Console.WriteLine("Area: {0}", r.GetArea()); Console.ReadLine(); } } } 功能),您的代码将如下所示。

datas

答案 1 :(得分:1)

我相信函数实例化意味着函数调用。

  

如果删除“r.Acceptdetails();或r.Display();”然后他们   不要实例化,输出不是预期的。

AcceptDetails方法正在为LengthWidth字段分配值。代码中没有其他地方可以为其分配任何值。因此,当您省略AcceptDetails的调用时,您将无法获得所需的结果。

Display方法调用实际执行计算的GetArea方法。

更重要的是,你做错了。在对象实例化时或在构造函数中分配值。 定义一个构造函数,如:

public Rectangle(double lengthParameter, double widthParamter)
{
    this.length = lengthParameter;
    this.width = widthParamter;
}

然后在Main方法中调用它,如:

Rectangle r = new Rectangle(4.5, 3.5);
r.Display();

作为旁注,请关注General Naming Conventions - MSDN,了解您的课程字段/属性。