【文章內(nèi)容簡介】
【例 56】 在下面程序中, MyArea類定義了兩個方法以求三角形和圓的面積 class MyAream { public double TangleArea(double a, double h) { double s。 s = a * h /2 。 return s。 } public double CircleArea(double r) { double s。 s = * r * r 。 return s。 } } 方法的參數(shù) 1.值參數(shù) 在方法聲明時不加修飾的形參數(shù),它表明實參與形參之間按值傳遞。 【例 57】 下面的程序演示了當方法 Sort傳遞的是值參數(shù)時,對形參的修改不影響其實參。 方法的參數(shù) class Program { static void Sort(int x, int y, int z) { int temp。 //將 x,y,z按從小到大排序 if (x y) { temp = x。 x = y。 y = temp。 } if (x z) { temp = x。 x = z。 z = temp。 } if (y z) { temp = y。 y = z。 z = temp。 } (a={0},b={1},c={2}, x, y, z)。 } static void Main(string[] args) { int a, b, c。 a = 20。 b = 10。 c = 5。 Sort(a, b, c)。 (a={0},b={1},c={2}, a, b, c)。 } } 方法的參數(shù) 2.引用參數(shù) 如果調(diào)用一個方法 , 期望能夠?qū)鬟f給它的實際變量進行操作 , 按值傳遞是不可能實現(xiàn)的 。 所以 C用了 ref修飾符來解決此類問題 , 它告訴編譯器 , 實參與形參的傳遞方式是引用 。 引用與值參數(shù)不同,引用參數(shù)并不創(chuàng)建新的存儲單元,它與方法調(diào)用中的實參變量同處一個存儲單元。因此,在方法內(nèi)對形參的修改就是對外部實參變量的修改。 【例 58】將例 57程序中 Sort方法的值參傳遞方式改成引用參數(shù)傳遞,觀察運行結(jié)果。 class Myclass { public void Sort(ref int x,ref int y,ref int z) { int temp。 //將 x,y,z按從小到大排序 if (x y) { temp = x。 x = y。 y = temp。 } if (x z) { temp = x。 x = z。 z = temp。 } if (y z) { temp = y。 y = z。 z = temp。 } (a={0},b={1},c={2}, x, y, z)。 } } class Program { static void Main(string[] args) { Myclass m = new Myclass()。 int a, b, c。 a = 20。 b = 10。 c =