拓展方法

适应环境:

第三方类不适合修改源码,通过拓展方法增加逻辑(如果自己的类中实例方法和拓展方法同名优先调用实例方法

适合组件式开发的拓展(.Net Core) 定义接口或者类 是按照最小需求 ,在开发时需要一些另外的方法, 就通过拓展方法

conent.Response.WriteAnsync 中间件的注册

Int? 的拓展方法:


     public static class ExtendInt{

        public static int ToInt(this int? i)
        {
                return i ?? 0;
        }
     }

没有约束的泛型类会污染,基础类型

 public static String ToStringCustom<T>(this T t)
        {
            if (t.GetType() = Guid)
            {
                return t.ToString().Replace("-", "");
            }
            //.....
            else{
                return t.ToString();
            }

        }

this 关键字只能放在第一个参数前面

拓展方法可以被子类继承

猜你喜欢

转载自blog.csdn.net/qq_36445227/article/details/90747544
今日推荐