標籤:
一 總結
1 方法分為靜態方法和非靜態方法,靜態方法不對特定的執行個體進行操作,且不允許引用this,非靜態方法是對類的某個特定的執行個體進行操作,且可以用this來訪改方法
例子一 靜態方法:
public static int add(int x,int y)
{
return x+y;
}
static void Main(string[] args)
{
Console.WriteLine(Program.add(3,4));
}
例子二 非靜態方法
public int add(int x,int y)
{
return x+y;
}
static void Main(string[] args)
{
Program program=new Program(); //執行個體化對象
Console.WriteLine(Program.add(3,4));
}
2 params關鍵字可以指定採用數目可變的參數的方法參數
註:一個函數中只能一個參數帶params關鍵字;
·帶params關鍵字的參數必須是最後一個參數;
·帶params關鍵字的參數類型必須是一維數組;
二 執行個體
1 求數組中最大元素值的方法
static void Main(string[] args)
{
int[] myArray = {1,5,3,7,8,22,21,33,35,99,26 };
int maxVal = MaxValue(myArray);
Console.WriteLine("The maximum value in myArray is {0}",maxVal);
Console.ReadKey();
}
static int MaxValue(int[] intArray)
{
int maxVal =intArray[0];
for (int i = 1; i < intArray.Length; i++)
{
if (intArray[i] > maxVal)
{
maxVal=intArray[i];
}
}
return maxVal;
}
2 求數組元素和的方法
static int SumVals(params int[] vals) //關鍵字params
{
int sum = 0;
foreach (int val in vals)
{
sum += val;
}
return sum;
}
static void Main(string[] args)
{
int sum = SumVals(1, 2, 3, 4, 5);
Console.WriteLine("The sum={0}", sum);
Console.ReadKey();
} }
3 物件導向和方法運用的小程式
using System;
class Address
{
public string name;
public string address;
}
class Methodparams
{
public static void Main()
{
string myChoice;
Methodparams mp = new Methodparams();
do
{
myChoice = mp.getchoice();
mp.makeDecision(myChoice);
Console.Write("Press any key to continue...");
Console.ReadLine();
Console.WriteLine();
} while (myChoice != "Q" && myChoice != "q");
}
string getchoice()
{
string mychoice;
Console.WriteLine("My Address Book\n");
Console.WriteLine("A-Add New Address");
Console.WriteLine("D-Delete Address");
Console.WriteLine("M-Modify Address");
Console.WriteLine("V-View Addresses");
Console.WriteLine("Q-Quit\n");
Console.WriteLine("Choice(A,D,M,V,Q)");
mychoice = Console.ReadLine();
return mychoice;
}
void makeDecision(string myChoice)
{
Address addr = new Address();
switch (myChoice)
{
case "A":
case "a":
addr.name = "Joe";
addr.address = "C# station";
this.addAddress(ref addr);
break;
case "D":
case"d":
addr.name="Robert";
this.deleteAddress(addr.name);
break;
case "M":
case "m":
addr.name="Matt";
this.modifyAddress(out addr);
Console.WriteLine("Name is now {0}",addr.name);
break;
case "V":
case "v":
this.viewAddress("Cheryl","Joe","Matt","Robert");
break;
case "Q":
case "q":
Console.WriteLine("Bye");
break;
}
}
void addAddress(ref Address addr)
{
Console.WriteLine("Name:{0},Address:{1} added.",addr.name,addr.address);
}
void deleteAddress(string name)
{
Console.WriteLine("You wish to delete {0}‘s address.",name);
}
void modifyAddress(out Address addr)
{
addr = new Address();
addr.name = "Joe";
addr.address = "C# Station";
}
void viewAddress(params string[] names)
{
foreach (string name in names)
{
Console.WriteLine("Name:{0}",name);
}
}
}
C#入門學習之屬性和方法