重載:
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);
}
}