1. 擴展方法
擴展方法是靜態方法,是類的一部分,但是實際上沒有放在類的源代碼中。
擴展方法所在的類也必須被聲明為static
C#只支持擴展方法,不支持擴展屬性、擴展事件等。
擴展方法的第一個參數是要擴展的類型,放在this關鍵字的后面,告訴編譯期這個方法是Money類型的一部分。
在擴展方法中,可以訪問擴展類型的所有公共方法和屬性。
using System;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
Money cash = new Money();
cash.Amount = 40M;
cash.AddToAmount(10M);
Console.WriteLine("cash.ToString() returns: " + cash.ToString());
Console.ReadLine();
}
}
public class Money
{
private decimal amount;
public decimal Amount
{
get
{
return amount;
}
set
{
amount = value;
}
}
public override string ToString()
{
return "$" + Amount.ToString();
}
}
public static class MoneyExtension
{
public static void AddToAmount(this Money money, decimal amountToAdd)
{
money.Amount += amountToAdd;
}
}
}
2. 外部方法
- 外部方法是在聲明中沒有實現的方法,實現被分號代替
- 外部方法使用extern修飾符標記
- 聲明和實現的連接是依賴實現的,但常常使用DllImport特性完成
class MyClass1 { [DllImport("kernel32",SetLastError=true)] public static extern int GetCurrentDirectory(int a, StringBuilder b); } class Program { static void Main(string[] args) { const int MaxDirLength = 199; StringBuilder sb = new StringBuilder(); sb.Length = MaxDirLength; MyClass1.GetCurrentDirectory(MaxDirLength, sb); Console.WriteLine(sb); Console.ReadLine(); } }
這段代碼產生以下輸出:
c:\users\v-lingc\documents\visual studio 2012\Projects\ConsoleApplication11\ConsoleApplication11\bin\Debug
