zoukankan      html  css  js  c++  java
  • this 关键字的用法

    用法一  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);
            }
        }

    运行结果:

    用法三  扩展方法

    用法四  索引器

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

  • 相关阅读:
    分子动力学中步长的选取
    提高编程能力刷题网站
    【18】如何把数据存储到MongoDB数据库
    【17】有关python面向对象编程的提高【多继承、多态、类属性、动态添加与限制添加属性与方法、@property】
    【16】有关python面向对象编程
    【15】杂记章节
    【14】文件读取并格式化处理
    【13】python time时间模块知识点备查
    【11】python 递归,深度优先搜索与广度优先搜索算法模拟实现
    6380. 【NOIP2019模拟2019.10.06】小w与最长路(path)
  • 原文地址:https://www.cnblogs.com/anyihen/p/9033323.html
Copyright © 2011-2022 走看看