演示代码:

public class Program
    {
        static void Main(string[] args)
        {
            var txt = "hello";
            Console.WriteLine(txt.GetString());
            var inttxt = "123";
            Console.WriteLine(inttxt.GetInt());
            var inttxt1 = "asd";
            Console.WriteLine(inttxt1.GetInt());
            Console.WriteLine("234".GetInt());
            Console.WriteLine("qwe".GetInt());
        }

    }

    public static class ExString
    {
        public static string GetString(this string source)
        {
            return source + "扩展方法";
        }

        public static int GetInt(this string source)
        {
            var outint = 0;
            if (!string.IsNullOrEmpty(source))
            {
                var result = int.TryParse(source,out outint);
                return outint;
            }
            return outint;
        }
    }

  代码输出:

 演示代码二:

public class Program
    {
        static void Main(string[] args)
        {
            var test = "dddd";
            Console.WriteLine(test.GetFuncString(x=>x=="123"));
            test = "123";
            Console.WriteLine(test.GetFuncString(x=>x=="123"));
        }


    }

    public static class ExString
    {

        public static string GetFuncString(this string source, Func<string, bool> type )
        {
            if (type(source))
            {
                return "true";
            }
            return source;
        }
    }

运行结果:

 

说明:

1、扩展方法是属于静态类的静态方法

2、第一个参数 this关键字,参数类型是需要扩展的类型

posted on 2015-04-05 16:29  fuyujian  阅读(192)  评论(0编辑  收藏  举报