扩展方法的小例子

来源:互联网 发布:照片后期制作app软件 编辑:程序博客网 时间:2024/05/19 00:50

扩展方法通俗的讲就是为一个类型增加一个新的方法,但是并不去修改该类型的结构。

下面举一个小例子

    public static class myClassExten
    {
        /*
         1.静态类
         2.静态方法
         3.this关键字
         
         */

    public static bool myBool(this int a) {


            bool reslut = false;
            if (a==1)
            {
                reslut = true;
            }
            return reslut;
        }


    }

这个静态类,为我当前程序集的int 提供了一个扩展方法。如果值为1时调用该方法返回True,否则返回1。


下面举一个委托的例子

   public static class myClassExten
    {
        /*
         1.静态类
         2.静态方法
         3.this关键字
         
         */

    public static List<string> myWhere(this List<string> list, Func<string, bool> funcWhere)
        {


            List<String> result = new List<string>();


            foreach (var item in list)
            {
                if (funcWhere(item))
                {


                    result.Add(item);
                }
            }
            return result;


        }

}


该方法为List<string> 增加了一个委托方法。


0 0