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

备注:本文讨论如何在类实例中使用 this。有关它在扩展方法中使用的详细信息,请参阅 C# 的 extension 关键字。

以下是 this 的常见用法:

  • 限定由相似名称隐藏的成员,例如:
public class KH
{
    private string 别名;
    private string 姓名;

    public KH ( string 姓名 , string 别名 )
    {
        // 使用这个来限定类的成员,而不是构造函数参数
        this . 姓名 = 姓名;
        this . 别名 = 别名; // 前一个别名被 this 限制为该实例的变量,后一个别名是构造函数的参数
    }
}
  • 将一个对象作为参数传递给其他方法,例如:
    FF ( this );
  • 欲声明索引器(indexer),例如:
public int this [ int C ]
{
    get => array [ C ];
    set => array [ C ] = value;
}

static 成员函数,因为它们存在于类级别,而不是作为对象的一部分,所以没有 this 指针。在静态方法中引用 this 是错误的。

在下例中,参数“姓名”和“别名”隐藏具有相同名称的字段。this 关键字将这些变量限定为“YG”类成员。this 关键字还指定“FF输出员工”方法的对象,该方法属于另一个类。

{
    public class YG
        {
            private string 姓名 , 别名;

            public YG ( string 姓名 , string 别名 )
                {
                    this . 姓名 = 姓名;
                    this . 别名 = 别名;
                }

            public YG ( string 姓名 )
                {
                    this . 姓名 = 姓名;
                    this . 别名 = "";
                }

            public void FF输出员工 ( )
                {
                    Console . WriteLine ( $"""
                                                姓名:{姓名}
                                                别名:{别名}
                                                """ );
                    Console . WriteLine ( $"税金:{Lei税 . FF计算税 ( this ):C}" );
                }

            public decimal 工资
                {
                    get;
                } = 3000.00m;
    }

public class Lei税
    {
        public static decimal FF计算税 ( YG k ) => 0.08m * k . 工资;
    }

static void Main(string[] args)
    {
        YG Msh = new ( "刘莉莉" , "小秘" );
        Msh . FF输出员工 ( );
    }
}

上例输出:
姓名:刘莉莉
别名:小秘
税金:¥240.00


兔子码农
4 声望1 粉丝

一个酒晕子