扩展方法的一点理解

在对已有类进行扩展时,我们需将所有扩展方法都写在一个静态类中,这个静态类就相当于存放扩展方法的容器,所有的扩展方法都可以写在这里面。而且扩展方法采用一种全新的声明方式: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

原文地址:https://www.cnblogs.com/skysimblog/p/3540335.html