1. 名詞解析:
(1) 重載: 是指創建多個名稱相同的方法,其中每個方法都有區別於其他方法的特征,以便編譯器區別和調用.
2. 程序清單如下:
// 通過重載方法來說明多態;
// 9_1_circle1.cs - polymorphic area method.
// -------------------------------------
using System;
public class Circle
{
public int x;
public int y;
public double radius;
private const float PI = 3.14159F;
public double Area() // 無參數的方法,返回以半徑為參數的圓的面積; --2--
{
return Area(radius);
}
public double Area(double rad) // 一個參數的方法;
{
double theArea;
theArea = PI * rad * rad;
Console.WriteLine("the areas for radius {0} is {1}", rad, theArea);
return theArea;
}
public double Area(int x1, int x2, double rad) // 三個參數的方法;
{
return Area(rad);
}
public double Area(int x1, int x2, int y1, int y2) // 四個參數的方法;
{
int x_diff;
int y_diff;
double rad;
x_diff = x2 - x1;
y_diff = y2 - y1;
rad = (double)Math.Sqrt((x_diff * x_diff) + (y_diff * y_diff));
return Area(rad);
}
public Circle() // 方法的默認參數; --1--
{
x = 0;
y = 0;
radius = 0;
}
}
class CirlceApp
{
public static void Main()
{
Circle myCircle = new Circle(); // 程序轉向--1--
Console.WriteLine("Passing nothing...");
myCircle.Area(); // 程序轉向--2--
Console.WriteLine("\nPassing a radius of 3...");
myCircle.Area(3);
Console.WriteLine("\nPassing a center of (2,4) and a radius of 3...");
myCircle.Area(2, 4, 3);
Console.WriteLine("\nPassing center of (2,3) and a point of (5,6)...");
myCircle.Area(2, 3, 5, 6);
}
}
3. 輸出結果:
Passing nothing...
the areas for radius 0 is 0
Passing a radius of 3...
the areas for radius 3 is 28.2743110656738
Passing a center of (2,4) and a radius of 3...
the areas for radius 3 is 28.2743110656738
Passing center of (2,3) and a point of (5,6)...
the areas for radius 1.4142135623731 is 6.28318023681641
4. ^_^ 初學C#,從書上敲出來的程序,有寫錯的地方望各位帥哥美女多多指教! 先謝了! ^_^
5. ^_^ 聯系方式: QQ : 601373891 Email : [email protected] 希望能我們成為朋友,共同進步. ^_^