C#:扩展方法

来源:互联网 发布:大学和老师谈恋爱知乎 编辑:程序博客网 时间:2024/06/06 03:49

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

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

 


<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>