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>
- 扩展方法(C#)
- 扩展方法,Objective-C
- C#:扩展方法
- C#.Net 扩展方法
- C#-- 扩展方法
- C#.NET扩展方法
- C#-----扩展方法
- [C#]扩展方法
- 【C#】C# 扩展方法
- C#==>扩展方法
- /*C#:扩展方法*/ 《自学系列》
- 【C#】——扩展方法
- c#——扩展方法
- 【C#】C#的扩展方法
- C#Extension Methods 扩展方法使用
- C 扩展
- c 扩展
- 扩展方法
- 线下推广网站的7种方法
- 千与千寻django(二)---永远的helloword
- ubuntu 上安装 oprofile
- SSL握手的具体流程
- windows网络编程笔记
- C#:扩展方法
- Android Service学习之IntentService 深入分析
- Linux3.4内核的基本配置和编译
- 自动关机批处理程序
- ANDROID更改CPU信息
- pthon 爬虫
- 对齐
- NPAPI插件开发详细记录:用VS2010开发NPAPI插件步骤
- 腾讯马拉松20号第一题