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

    导读

    本文将列举C#中this关键字的用途

    1、this 含义

    2、用this 关键字避免参数与字段的混淆

    3、用this关键字串联构造器

    4、索引器

    6、Visitor 模式


    this 含义

    C# 允许在类的所有实例方法中使用 this 关键字。this 关键字表示对当前对象的引用,因此this不允许出现在静态方法中。

     

    用 this 关键字避免参数与字段的混淆

    在方法体中,类实例成员可以通过 this 访问,不带this 前缀的标识符优先为参数名。看代码

    static class App
    {
        static void Main()
        {
            Lib l = new Lib();
            l.ChangArg("222");
        }
    }
    
    class Lib
    {
        private string arg;
        
        public void ChangArg(string arg)
        {
            arg = arg;    // 会有警告 this.arg = arg; 便可避免
        }
    }

     

    用this关键字串联构造器

    将所有构造器的主要逻辑提取出来放在一个构造器内,其他构造器按照参数调用即可,看代码

    using System;
    
    static class App
    {
        static void Main()
        {
            Lib l1 = new Lib();
            l1.Print();
            
            Lib l2 = new Lib(new object());
            l2.Print();
        }
    }
    
    class Lib
    {
        private object _args ;
        // this 串联构造器
        public Lib():this(null){}
        public Lib(object args)
        {
            this._args = args;
        }
    
        public void Print()
        {
            Console.WriteLine(_args==null?"非空构造器生成":"空构造器生成");
        }
    }

     

    索引器

    索引器的语法中用到this,看代码

    using System;
    using System.Collections.Generic;
    
    static class App
    {
        static void Main()
        {
            Lib l = new Lib();
            Console.WriteLine(l[0]);    // 用索引器
        }
    }
    
    class Lib
    {
        private List<string> _list;
        public Lib()
        {
            _list = new List<string>();
            _list.Add("Apple");
            _list.Add("MS");
            _list.Add("Google");
        }
        // 定义索引器
        public string this[int index]
        {
            get
            {
                if(index >=0 && index <= 2)
                {
                    return _list[index];
                }
                return null;
            }
        }
    }

     

    Visitor 模式

    this 关键字的一个用法是将当前对象的引用传递给其他方法,甚至其他的类,通常这种方法预示着扩展架构,如 Visitor 模式,看代码

    class Foo
    {
        // 一个实例方法
        void fct()
        {
            fct2(this);
        }
        
        static void fct2(Foo foo)
        {
            // 操作foo实例,可能对其扩展
        }
    }

     

    本文完

  • 相关阅读:
    springMvc
    计算机网络
    Mybatis 总结
    Spring 面试总结
    Java IO 流
    自定义类加载器
    缓存一致性协议
    dfs、bfs序
    7.26
    Trick
  • 原文地址:https://www.cnblogs.com/Aphasia/p/4333781.html
Copyright © 2011-2022 走看看