• C#中扩展方法


    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)
  • 相关阅读:
    Nginx下配置SSL安全协议
    Java嵌套类
    python命名空间与作用域
    Effective Java 4:类和接口
    VIM快捷键(转载)
    Eclipse快捷键
    Effective Java 3:对于所有对象都通用的方法
    Effective Java 1:创建和销毁对象-续
    Effective Java 1:创建和销毁对象
    python文件操作(转载)
  • 原文地址:https://www.cnblogs.com/yeagen/p/2666233.html
Copyright © 2020-2023  润新知