C#:擴展方法和外部方法ide
一..擴展方法ui
1.擴展方法是靜態方法,是類的一部分,可是實際上沒有放在類的源代碼中。this
2.擴展方法所在的類也必須被聲明爲staticspa
3.C#只支持擴展方法,不支持擴展屬性、擴展事件等。事件
4.擴展方法的第一個參數是要擴展的類型,放在this關鍵字的後面,告訴編譯期這個方法是Money類型的一部分。ci
5.在擴展方法中,能夠訪問擴展類型的全部公共方法和屬性。get
using System;string
namespace ConsoleApplication5it
{io
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;
}
}
}
二. 外部方法
外部方法是在聲明中沒有實現的方法,實現被分號代替
外部方法使用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();
}
}