C#:扩展方法和外部方法


一..扩展方法



1.扩展方法是静态方法,是类的一部分,但是实际上没有放在类的源代码中。


2.扩展方法所在的类也必须被声明为static


3.C#只支持扩展方法,不支持扩展属性、扩展事件等。


4.扩展方法的第一个参数是要扩展的类型,放在this关键字的后面,告诉编译期这个方法是Money类型的一部分。


5.在扩展方法中,可以访问扩展类型的所有公共方法和属性。





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;

        }

    }

}


二. 外部方法


外部方法是在声明中没有实现的方法,实现被分号代替

外部方法使用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();

        }

    }