zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    C# Array.Sort 省内排序
    Centos7开机启动tomcat8
    使用GeoWebCache发布ArcGIS切片地图(实现高清电子地图)
    获取经纬度之间距离的Java工具类
    centos7上安装rar解压软件
    GeoServer之发布Geotiff存在的问题
    $GPRMC解析
    如何在IDEA单元测试中使用Scanner获取输入内容
    GeoServer修改使用内存
    Github无法访问解决办法
  • 原文地址:https://www.cnblogs.com/yeagen/p/2666233.html
Copyright © 2011-2022 走看看