c#对一个类的扩展

首先定义一个静态类,参数使用this约束并选择需要扩展的类,当然也可以 继续添加扩展是需要添加的参数

 public static class StringExrprp
    {
        /// <summary>
        /// 判定字符串是否有值
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool HasValue(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }
            return true;
        }
    }

使用的时候string类就有了我们扩展的方法

 static void Main(string[] args)
        {
            string str = "test";
            Console.WriteLine(str.HasValue());
            //对比原始使用方法
            Console.WriteLine(string.IsNullOrEmpty(str));
            Console.ReadLine();
        }

这里只是抛砖引玉,更多实用的扩展可以帮助我们更好的更快的去实现代码。

 

posted @ 2017-07-08 22:55  站在走廊弹吉他  阅读(599)  评论(0编辑  收藏  举报