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();
}
}