Billpeng Space

技术源自生活
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#中扩展方法

Posted on 2012-09-01 01:23  billpeng  阅读(303)  评论(0编辑  收藏  举报
C# 3.0 里提供了这种机制,可以为类添加属性或者方法,比如说为 String 添加一个方法


namespace MyExtensionMethods {
    public static class MyExtensions {
        public static int MyGetLength(this System.String target)
        {
            return target.Length;
        }
    }
}

 

分组的方法:

public static class StringExtension
     {
         public static ChineseString AsChineseString(this string s) { return new ChineseString(s); }
         public static ConvertableString AsConvertableString(this string s) { return new ConvertableString(s); }
         public static RegexableString AsRegexableString(this string s) { return new RegexableString(s); }
     }
     public class ChineseString
     {
         private string s;
         public ChineseString(string s) { this.s = s; }
         //转全角
         public string ToSBC(string input) { throw new NotImplementedException(); }
         //转半角
         public string ToDBC(string input) { throw new NotImplementedException(); }
         //获取汉字拼音首字母
         public string GetChineseSpell(string input) { throw new NotImplementedException(); }
     }
     public class ConvertableString
     {
         private string s;
         public ConvertableString(string s) { this.s = s; }
         public bool IsInt(string s) { throw new NotImplementedException(); }
         public bool IsDateTime(string s) { throw new NotImplementedException(); }
         public int ToInt(string s) { throw new NotImplementedException(); }
         public DateTime ToDateTime(string s) { throw new NotImplementedException(); }
     }
     public class RegexableString
     {
         private string s;
         public RegexableString(string s) { this.s = s; }
         public bool IsMatch(string s, string pattern) { throw new NotImplementedException(); }
         public string Match(string s, string pattern) { throw new NotImplementedException(); }
         public string Relplace(string s, string pattern, MatchEvaluator evaluator) { throw new NotImplementedException(); }
     }
 



使用时,需要引入这个名字空间,引用如下:
C# code
string str = "dafasdf"; int len = str.MyGetLength();


扩展方法的声明方式:
1. 静态类,静态方法
2. 第一个参数是目标类的一个实例,需要使用 this 关键字

其他问题,请参考 .net 3.0 的特性。 (请使用vs2008)