码迷,mamicode.com
首页 > 其他好文 > 详细

this 关键字的用法

时间:2018-05-13 21:35:20      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:http   扩展方法   nal   void   ext   []   text   实例   bsp   

用法一  this代表当前类的实例对象

 class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Test test = new Test();
                Console.WriteLine(test.getResult());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.ReadLine();
            }

        }
    }

    public class Test
    {
        private string scope = "全局变量";
        public string getResult()
        {
            string scope = "局部变量";
            // this代表Test的实例对象
            // 所以this.scope对应的是全局变量
            // scope对应的是getResult方法内的局部变量
            return this.scope + "-" + scope;
        }
    }

运行结果:

技术分享图片

// 用法二  用this串联构造函数
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // this()对应无参构造方法Test()
                // 先执行Test(),后执行Test(string text)
                Test test = new Test("s");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.ReadLine();
            }

        }
    }

    public class Test
    {
        public Test()
        {
            Console.WriteLine("默认无参构造");
        }
        public Test(string s):this()
        {
            Console.WriteLine("有参构造:"+s);
        }
    }

运行结果:

技术分享图片

用法三  扩展方法

用法四  索引器

 后两种,具体后续详细描述

this 关键字的用法

标签:http   扩展方法   nal   void   ext   []   text   实例   bsp   

原文地址:https://www.cnblogs.com/anyihen/p/9033323.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!