扩展方法

namespace ExtendMethods

{

    public static class ExtendMethod

    {

        //定义string类型的扩展方法IsRight()

        public static bool IsRight(this string str)

        {

            switch (str.ToUpper().Trim())

            {

                case "RIGHT":

                    return true;

                case "YES":

                    return true;

                case "OK":

                    return true;

                default:

                    return false;

            }

        }

 

        //定义int类型的扩展方法IsRight()

        public static bool IsRight(this int str)

        {

            if (str > 10)

            {

                return true;

            }

            else

            {

                return false;

            }

        }

 

        //定义一个对于所有类型的扩展方法,打印类信息的同时添加一个字符串作为提示信息

        public static void PrintHint(this object obj, string hint)

        {

            System.Console.WriteLine(obj.ToString() + "--" + hint);

        }

    }

}

 

namespace ExtendMethods

{

    class Program

    {

        static void Main(string[] args)

        {

            //使用string类型的扩展方法IsRight()

            string str1 = "right", str2 = "err";

            System.Console.WriteLine("str1.IsRight()=" + str1.IsRight().ToString());

            System.Console.WriteLine("str2.IsRight()=" + str2.IsRight().ToString());

 

            //使用int类型的扩展方法IsRight()

            int i1 = 11, i2 = 5;

            System.Console.WriteLine("i1.IsRight()=" + i1.IsRight().ToString());

            System.Console.WriteLine("i2.IsRight()=" + i2.IsRight().ToString());

 

            //使用Object类型的扩展方法PringHint()

            string str3 = "biao";

            str3.PrintHint("Hello!");

        }

    }

}

posted @ 2010-12-29 12:44  liumeibiao  阅读(164)  评论(0编辑  收藏  举报