C#【补充】this关键字

本文详细探讨了this在C#编程中的使用,包括限定隐藏成员、对象参数传递和索引器声明,通过实例演示如何利用this有效组织类结构并提升代码可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一、this常见用法

this 关键字指代类的当前实例,还可用作扩展方法的第一个参数的修饰符【需要另行学习】

以下是 this 的常见用法:

限定类中隐藏的成员

例如:

public class Employee
{
    private string alias;
    private string name;

    public Employee(string name, string alias)
    {
        // Use this to qualify the members of the class
        // instead of the constructor parameters.
        this.name = name;
        this.alias = alias;
    }
}

将对象作为参数传递给方法

例如:

CalcTax(this);

声明索引器

例如:

public int this[int param]
{
    get { return array[param]; }
    set { array[param] = value; }
}

特别说明
静态成员函数,因为它们存在于类级别且不属于对象,不具有 this 指针。 在静态方法中引用 this 会生成错误。【即在静态成员函数(包含static关键字)中不能引用/出现this关键字

二、示例

在此示例中,this 用于限定类似名称隐藏的 Employee 类成员、name 和 alias。 它还用于将某个对象传递给属于其他类的方法 CalcTax。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    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}\nAlias: {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();

            Console.ReadLine();
        }
    }
    /*
    Output:
        Name: Mingda Pan
        Alias: mpan
        Taxes: $240.00
     */
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElecNoon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值