C#中 this关键字用法

    public static class StringExtention
    {
        public static string ToBase64(this string s)
        {
            return s.ToBase64(Encoding.UTF8);
        }
        public static string ToBase64(this string s, Encoding encoding)
        {
            if (string.IsNullOrWhiteSpace(s))
                return string.Empty;

            var bytes = encoding.GetBytes(s);
            return Convert.ToBase64String(bytes);
        }
    }

定义一个 string 类型的扩展类 

满足扩展类必须是静态类

        static void Main(string[] args)
        {
            string str = "12123";
            Console.WriteLine(str.ToBase64());
            Console.ReadKey();
        }

调用方式,一次扩展,项目中各处逻辑都能调用这个扩展,很便捷

详解:方法入参中 this  代之当前对象,这个方法就是通过this关键字 指向本体对象进行逻辑处理

posted @ 2020-08-21 10:38  秋风野马  阅读(224)  评论(0编辑  收藏  举报