zoukankan      html  css  js  c++  java
  • this(C#)

    this 关键字用于引用类的当前实例,还可用作扩展方法的第一个参数的修饰符。

    以下是 this 的常用用途:

    • 限定被相似的名称隐藏的成员,如下,以下两段代码功能相同:
    public Employee(string name, string alias)
    {
        // Use this to qualify the fields, name and alias:
        this.name = name;
        this.alias = alias;
    }
    ----------
    public Employee(string m_name, string m_alias)
    {
        // Use this to qualify the fields, name and alias:
        this.name = m_name;
        this.alias = m_alias;
    }
    
    
    • 将对象作为参数传递到其他方法,例如:
    CalcTax(this);
    • 声明索引器,例如:
    public int this[int param]
    {
        get { return array[param]; }
        set { array[param] = value; }
    }
    • 由于静态成员函数存在于类一级,并且不是对象的一部分,因此没有 this 指针。 在静态方法中引用 this 是错误的。

    示例:
    在本例中,this 用于限定 Employee 类成员 name 和 alias,它们都被相似的名称隐藏。 该关键字还用于将对象传递到属于其他类的方法 CalcTax。

     class Employee
            {
                private string name;
                private string alias;
                private decimal salary = 3000.00m;
    
                // Constructor:
                public Employee(string name, string alias)
                {
                    // Use this to qualify the fields, name and alias:
                    this.name = name;
                    this.alias = alias;
                }
                // Printing method:
                public void printEmployee()
                {
                    Console.WriteLine("Name: {0}
    Alias: {1}", name, alias);
                    // Passing the object to the CalcTax method by using this:
                    Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
                }
    
                public decimal Salary
                {
                    get { return salary; }
                }
            }
    
            class Tax
            {
                public static decimal CalcTax(Employee E)
                {
                    return 0.08m * E.Salary;
                }
            }
    
            class MainClass
            {
                static void Main()
                {
                    // Create objects:
                    Employee E1 = new Employee("Mingda Pan", "mpan");
    
                    // Display results:
                    E1.printEmployee();
                }
            }
            /*
            Output:
                Name: Mingda Pan
                Alias: mpan
                Taxes: $240.00
             */
    

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    kolla多节点部署openstack
    归并排序
    gitlab ci/cd
    微信、支付宝个人收款码不能用于经营收款 z
    微信小程序弹出和隐藏遮罩层动画以及五星评分
    centos7 安装 nginx
    netty+websocket模式下token身份验证遇到的问题
    windows 截图 win+shift+s
    linux下 "chmod 777" 中777这个数字是怎么出来的
    nginx四层转发,访问内网mysql数据库
  • 原文地址:https://www.cnblogs.com/gongchuangsu/p/4850195.html
Copyright © 2011-2022 走看看