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

    原文地址:https://msdn.microsoft.com/zh-cn/library/dk1507sz.aspx

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

    System_CAPS_note注意

    本文讨论对类实例使用 this。 有关其在扩展方法中使用的更多信息,请参见扩展方法(C# 编程指南)

    以下是 this 的常用用途:

    • 限定被相似的名称隐藏的成员,例如:

     
    public Employee(string name, string alias)
    {
        // Use this to qualify the fields, name and alias:
        this.name = name;
        this.alias = 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
     */
    
  • 相关阅读:
    OpenCV 环境搭建( Win7 32位 / VS2010 / OpenCV2.4.8 )
    OpenCV 简介
    计算机视觉简介
    使用 sigaction 函数实现可靠信号
    可靠信号机制
    信号机制的两个思考
    信号的接收和处理
    【angular5项目积累总结】列表多选样式框(1)
    数组相关方法积累(vueag等特别常用)
    Angular 4+ 修仙之路
  • 原文地址:https://www.cnblogs.com/Arlar/p/6032561.html
Copyright © 2011-2022 走看看