• C#this的五种用法


    this的五种用法:

    1.使用被掩盖的成员变量:

    class AA

    {

            int a;

            public void set1(int a)

            {

                this.a = a;//right

            }

            public void set2(int a)

            {

                a = a;//会有警告:“对同一变量进行赋值;是否希望对其他变量赋值?”;

            }

    }

    2.把这个对象传给其他函数

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class BB
        {
            static public void set(AA t,int a)
            {
                t.set1(a);
            }
        }
        class AA
        {
            int a;
            public void set1(int a)
            {
                this.a = a;
            }
            public void set2(int a)
            {
                BB.set(this, a);
            }
            public int get()
            {
                return a;
            }
        }
        
        class Program
        {
            static void Main(string[] args)
            {
                AA t = new AA();
                t.set2(123);
                Console.WriteLine(t.get());
            }
        }
    }

    3.With Indexers(索引器)//这个暂时不懂

    4.调用其他构造函数

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication2
    {
        class AA
        {
            int a, b;
            public AA(int a)
            {
                this.a = a;
                b = -1;
                print();
            }
            public AA(int a,int b):this(a)
            {
                this.b = b;
                print();
            }
            void print()
            {
                Console.WriteLine("{0} {1}", a, b);
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                AA t = new AA(1);
                t = new AA(1, 1);
            }
        }
    }

    输出:

    1 -1

    1 -1

    1 1

    5.是代码更明确

    如把

            public AA(int a)
            {
                this.a = a;
                b = -1;
                print();
            }    

    改为

            public AA(int a)
            {
                this.a = a;
                this.b = -1;
                print();
            }
  • 相关阅读:
    pandas基础操作(一)
    将字符串中的字符映射不同的值,并保存txt文本
    and、or、not、in、not in 中的or
    pandas读写数据库
    SQL语句被锁,运行超时
    在一张表里添加另外一张表里的一列数据
    Linux服务进程管理
    Ubuntu软件更新更换源
    SpringBoot1-1
    Linux 基本使用2
  • 原文地址:https://www.cnblogs.com/wos1239/p/4382045.html
Copyright © 2020-2023  润新知