zoukankan      html  css  js  c++  java
  • 扩展方法的一点理解

    在对已有类进行扩展时,我们需将所有扩展方法都写在一个静态类中,这个静态类就相当于存放扩展方法的容器,所有的扩展方法都可以写在这里面。而且扩展方法采用一种全新的声明方式:public static 返回类型 扩展方法名(this 要扩展的类型 sourceObj [,扩展方法参数列表]),与普通方法声明方式不同,扩展方法的第一个参数以this关键字开始,后跟被扩展的类型名,然后才是真正的参数列表。

    public static class StringExtension
        {
            public static bool EqualsIgnoreCase(this string s, string another)
            {
                return s.Equals(another, StringComparison.OrdinalIgnoreCase);
            }
    
            public static bool ContainsIgnoreCase(this string source, string another)
            {
                if (source == null)
                {
                    throw new ArgumentException("source");
                }
                return source.IndexOf(another, StringComparison.OrdinalIgnoreCase) >= 0;
            }
    
            public static bool Matches(this string source, string pattern)
            {
                if (string.IsNullOrEmpty(source))
                {
                    throw new ArgumentException("source");
                }
                if (string.IsNullOrEmpty(pattern))
                {
                    throw new ArgumentNullException("pattern");
                }
                return Regex.IsMatch(source, pattern);
            }
                }
    public static class DictionaryExtension
        {
    
            public static bool TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
            {
                if (ReferenceEquals(dict, null))
                {
                    throw new ArgumentNullException("dict");
                }
    
                if (dict.ContainsKey(key))
                {
                    return false;
                }
                else
                {
                    dict.Add(key, value);
                    return true;
                }
            }
    
            public static void AddOrReplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
            {
                if (ReferenceEquals(dict, null))
                {
                    throw new ArgumentNullException("dict");
                }
                dict[key] = value;
            }
               }

    参考http://www.cnblogs.com/abcdwxc/archive/2007/11/21/967580.html

  • 相关阅读:
    sql——查询出表中不为空或为空字段的总值数
    sql语句——根据身份证号提取省份、出生日期、年龄、性别。
    1.两数之和
    Java虚拟机
    【10.18】
    议论文:是否应该留学
    议论文:阅读能力
    应用文:线上广告
    通知(重点:格式)
    书信(重点:格式)
  • 原文地址:https://www.cnblogs.com/skysimblog/p/3540335.html
Copyright © 2011-2022 走看看