無參、無返回值的函數:
using System;
class MyClass
{
static void Show()
{
Console.WriteLine("function");
}
static void Main()
{
Show(); //function
Console.ReadKey();
}
}
參數:
using System;
class MyClass
{
static void Show(string str)
{
Console.WriteLine("is " + str);
}
static void Main()
{
show("function"); //is function
Console.ReadKey();
}
}
返回值:
using System;
class MyClass
{
static string Show(string str)
{
return "is " + str;
}
static void Main()
{
string s = Show("function");
Console.WriteLine(s); //is function
Console.ReadKey();
}
}
函數見 return 就返回:
using System;
class MyClass
{
static int Math(int x, int y)
{
return x + y;
return x * y; /* 執行不了這句 */
}
static void Main()
{
Console.WriteLine(Math(3,4)); //7
Console.ReadKey();
}
}
數組參數:
using System;
class MyClass
{
static int ArrMax(int[] arr)
{
int max = arr[0];
for (int i = 1; i < arr.Length; i++)
if (arr[i] > max) max = arr[i];
return max;
}
static void Main()
{
int[] ns = { 1,2,3,4,5,4,3,2,1 };
Console.WriteLine(ArrMax(ns)); //5
Console.ReadKey();
}
}
參數數組(關鍵字 params):
using System;
class MyClass
{
static int Sum(params int[] arr)
{
int count = 0;
foreach(int i in arr) count += i;
return count;
}
static void Main()
{
int n = Sum(1,2,3);
Console.WriteLine(n); //6
n = Sum(1,2,3,4,5,6,7,8,9);
Console.WriteLine(n); //45
Console.ReadKey();
}
}
引用參數和輸出參數:
using System;
class MyClass
{
static void proc1(ref int num)
{
num = num * num;
}
static void proc2(out int num)
{
num = 100;
}
static void Main()
{
int a = 9;
proc1(ref a); /* 引用參數(ref) 參數必須是已初始化的 */
Console.WriteLine(a); //81
int b;
proc2(out b); /* 輸出參數類似 ref(但初始化不是必要的), 是從函數中接出一個值來 */
Console.WriteLine(b); //100
Console.ReadKey();
}
}
重載:
using System;
class MyClass
{
static int Add(int n1, int n2)
{
return n1 + n2;
}
static string Add(string s1, string s2)
{
return s1 + s2;
}
static void Main()
{
Console.WriteLine(Add(111,222)); //333
Console.WriteLine(Add("111", "222")); //111222
Console.ReadKey();
}
}
委托(我覺得委托就是把函數當作一種類型的手段):
using System;
class MyClass
{
delegate double MyFunType(double n1, double n2);
static double Add(double n1, double n2) { return n1 + n2; }
static double Dec(double n1, double n2) { return n1 - n2; }
static double Mul(double n1, double n2) { return n1 * n2; }
static double Div(double n1, double n2) { return n1 / n2; }
static void Main()
{
MyFunType Fun;
Fun = new MyFunType(Add); Console.WriteLine(Fun(3, 2)); // 5
Fun = new MyFunType(Dec); Console.WriteLine(Fun(3, 2)); // 1
Fun = new MyFunType(Mul); Console.WriteLine(Fun(3, 2)); // 6
Fun = new MyFunType(Div); Console.WriteLine(Fun(3, 2)); // 1.5
Console.ReadKey();
}
}
調用外部函數:
using System;
using System.Runtime.InteropServices;
class MyClass
{
[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);
static void Main()
{
string str = "Visual Studio 2008!";
MessageBox(0, str, "信息提示", 0);
}
}