2016-04-04 72 views
-2
using System; 
namespace RectangleApplication 
{ 

class Rectangle 
{ 
     double length; //Creating the length and width variables  
     double width;  

    public void AcceptDetails() //Getting the details of length and width set in stone 
    { 
    length = 4.5; 
    width = 3.5; 
    } 

    public double GetArea() //Multiplying and returning the product of length and width 
    { 
     return length * width; 
    } 

    public void Display() //Displaying the results 
    { 
     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.ReadKey(); 
    } 
} 
} 

這不是我的程序,我從TutorialsPoint.com獲得它。我理解所有的代碼,直到它到達ExecuteRectangle類,它實例化Rectangle類。需要幫助瞭解C#矩形程序

Rectangle r = new Rectangle(); 
r.AcceptDetails(); 
r.Display(); 

你會用這個做什麼? r.AcceptDetails()r.Display()是做什麼的?

感謝您的閱讀並抱歉,如果帖子馬虎。

這是我的第一個。

+2

不確定你在問什麼。你在Rectangle類中有'AcceptDetails()'和'Display()'方法,所以你可以看到他們在做什麼。一個設置一些變量,另一個顯示它們。 –

+0

閱讀評論,並運行程序請:)評論解釋程序相當好。 – nevets

+0

我在問爲什麼他們在ExecuteRectangle類中。我知道什麼是Display()和AcceptDetails()。 – tristbill

回答

0

到首先使用封裝在矩形類中的所有代碼(即類Rectangle {...}),您必須先創建該類的實例。

Rectangle r = new Rectangle(); 

這是類矩形的這種情況下,其中「R」是實例

的名稱然後使用方法,你需要引用實例(R類的聲明。 )然後是你想要訪問的方法。

-1

所以AcceptDetails()組的長度和寬度爲以下:

length = 4.5; 
width = 3.5; 

Display()將輸出使用Console.WriteLine()

Console.WriteLine("Length: {0}", length); --> Print length 
    Console.WriteLine("Width: {0}", width); --> Print Width 
    Console.WriteLine("Area: {0}", GetArea()); -> Print length * width 

該應用程序是非常自我解釋和碼具有這樣的結果到控制檯窗口解釋發生了什麼的評論。我建議你多做一點研究。

-1

如主方法上面的方法所示,AcceptDetails()的調用將長度和寬度的值分別設置爲4.5和3.5。

然後Display()方法被調用之後,它寫入控制檯的長度,寬度和然後的區域中,這是由GetArea()方法實時計算,它乘該長度和寬度一起

的語法的AcceptDetails();(或任何其他使用的方法)用於調用的方法,該方法將運行方法定義內的代碼。

定義是,是這樣的

private void AcceptDetails() 
{ 
    length = 4.5; 
    width = 3.5; 
} 

這就告訴是什麼應該做的,在此情況下設定的長度和寬度的方法的代碼。

此代碼

AcceptDetails(); 

正在運行的方法,無需鍵入的內容,因此它是一樣一樣的因爲這已經在方法被預定義這樣

length = 4.5; 
width = 4.5; 

,它可以直接調用以避免多次輸入代碼。

推而廣之,這

static void Main(string[] args) 
{ 
    Rectangle r = new Rectangle(); 
    r.AcceptDetails(); 
    r.Display(); 
    Console.ReadKey(); 
} 

實際上等同於這個

static void Main(string[] args) 
{ 
    double length; 
    double width; 
    length = 4.5; 
    width = 3.5; 
    Console.WriteLine("Length: {0}", length); 
    Console.WriteLine("Width: {0}", width); 
    Console.WriteLine("Area: {0}", length * width); 
    Console.ReadKey(); 
} 

這樣做的好處是,它是非常可重複使用的,並且是非常整潔,正確編碼