c# 扩展方法

{    /// <summary>
     // 扩展方法:静态类里面的静态方法,第一个参数类型前面加上this
    //1 第三方的类,不适合修改源码,可以通过扩展方法增加逻辑
    //优先调用实例方法,最怕扩展方法增加了,别人类又修改了
    //2 适合组件式开发的扩展(.NetCore),定义接口或者类,是按照最小需求,但是在开发的时候又经常需要一些方法,就通过扩展方法 context.Response.WriteAsync  中间件的注册
    //3 扩展一些常见操作
    /// </summary>
    public static class ExtendMethod
    {
        //int为空返回0
        public static int ToInt(this int? i)
        {
            return i ?? 0;
        }

        //截取字符串
        public static string ToLength(this string text, int length = 15)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return "";
            }
            else if (text.Length > length)
            {
                return ($"{text.Substring(0, length)}...");
            }
            else
            {
                return text;
            }
        }
        //会污染基础类型,一般少为object  没有约束的泛型去扩展
        //public static string ToStringCustom<T>(this T t)
        //{
        //    if (t is Guid)
        //    {
        //        return t.ToString().Replace("-", "");
        //    }
        //    //.....
        //    else
        //    {
        //        return t.ToString();
        //    }
        //}

        //public static string ToStringNew(this object o)
        //{
        //    if (o is null)
        //    {
        //        return "";
        //    }
        //    else
        //    {
        //        return o.ToString();
        //    }
        //}

    }
}
   class Program
    {

        static void Main(string[] args)
        {
            {
                int? i = 10;
                Console.WriteLine(i.ToInt());
            }
            {
                int? i = null;
                Console.WriteLine(i.ToInt());
            }
                
            {
                string text = "此时已莺飞草长爱的人正在路上";
                Console.WriteLine(text.ToLength(10));
            }
            Console.Read();
        }
    }
原文地址:https://www.cnblogs.com/wangdash/p/11825960.html