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)
  • 相关阅读:
    LeetCode-top100-3. 无重复字符的最长子串
    最长单调递增子序列 POJ 3903 Stock Exchange .
    并查集 POJ 1988 Cube Stacking
    贪心初步 hdu1789 Doing Homework again
    并查集初步题目(2)
    并查集初步题目(1)
    【python】引用模块,以及初探__init__.py
    Python 模块里函数的调用方法和import语句的作用(初学者版)
    二分查找算法
    python之内置函数,匿名函数
  • 原文地址:https://www.cnblogs.com/yeagen/p/2666233.html
Copyright © 2011-2022 走看看