C#中的"this"是什么意思?

9

请问在C#中,“this”是什么意思?

例如:

// complex.cs
using System;

public struct Complex 
{
   public int real;
   public int imaginary;

   public Complex(int real, int imaginary) 
   {
      this.real = real;
      this.imaginary = imaginary;
   }

5
为什么不查看MSDN呢?“this关键字指的是当前类的实例。” - Vlad
8
为什么不在stackoverflow上发布? - JonH
1
@Vlad - 这是许多在SO上提出的问题都适用的一个问题。SO的目的是成为一个可作为参考的地方。首先,并不是每个人都知道MSDN(因此指向那里是一个好主意)。其次,OP已经给出了上下文。在我看来,这是一个有效的问题。 - keyboardP
3
搜索常见词汇,比如“this”非常困难。你是否真的去MSDN网站搜索过“this”并查看搜索结果?这几乎就像是找出if-then语句中的?和??的含义,或者lambda表达式中的=>一样困难。 - DOK
我认为这个问题是合理的,虽然我肯定不难通过谷歌找到关于this的参考资料:c# this返回了很多好的结果(包括MSDN)。 - Chris Walsh
显示剩余6条评论
8个回答

20

this关键字是指当前类的实例。

在您的示例中,this用于引用类Complex的当前实例,并消除了构造函数签名中的int real与类定义中的public int real;之间的歧义。

MSDN有一些文档也值得查看。

虽然与您的问题没有直接关系,但在扩展方法中还有另一个使用this作为第一个参数的用法。它用作第一个参数,表示要使用的实例。如果想要向String类添加方法,只需在任何静态类中编写即可。

public static string Left(this string input, int length)
{
    // maybe do some error checking if you actually use this
    return input.Substring(0, length); 
}

参见: http://msdn.microsoft.com/en-us/library/bb383977.aspx


3
当方法体被执行时
public Complex(int real, int imaginary) {
    this.real = real;
    this.imaginary = imaginary;
}

正在执行的代码是在一个名为Complex的结构体的特定实例上执行。您可以使用关键字this来引用该代码所执行的实例。因此,您可以将该方法的主体视为:

public Complex(int real, int imaginary) {
    this.real = real;
    this.imaginary = imaginary;
}

作为阅读

public Complex(int real, int imaginary) {
    assign the parameter real to the field real for this instance
    assign the parameter imaginary to the field imaginary for this instance
}

通常都有一个隐含的 this,所以以下语句等效:

class Foo {
    int foo;
    public Foo() {
        foo = 17;
    }
}

class Foo {
    int foo;
    public Foo() {
        this.foo = 17;
    }
}

然而,本地变量优先于成员变量。
class Foo {
    int foo;
    public Foo(int foo) {
        foo = 17;
    }
}

17赋值给作为方法参数的变量foo。如果您想要在方法中为实例成员赋值,而该方法存在与该成员同名的局部变量,则必须使用this来引用它。


1

this引用了该类的实例。


1

为什么要包含代码图片?Stack Overflow 从一开始就具备了包含以代码格式排版的文本的能力... - Heretic Monkey

1
由于大多数答案都提到了“类的当前实例”,对于新手来说,“实例”可能很难理解。 “类的当前实例”指的是在定义它的类中特定使用this.varible,而不是其他任何地方。因此,如果变量名也出现在类之外,开发人员不需要担心由于多次使用相同的变量名而带来的冲突/混淆。

你得到了真正缺失的空格<>。 - Amitya Narayan

1
Nate和d_r_w有答案。 我只想补充一点,即在您的代码中,this.确实是指类的成员,以区别于函数的参数。因此,该行
this.real = real

意味着将函数(在本例中是构造函数)参数'real'的值分配给类成员'real'。通常你也会使用case语句来使区分更清晰:

public struct Complex
{
    public int Real;
    public int Imaginary;
    public Complex(int real, int imaginary)
    {
        this.Real = real;
        this.Imaginary = imaginary;
    }
}

1
如果您的参数名称与字段名称不同,则实际上不需要使用 this。但对于 OP 的示例,使用 this 是强制性的。 - Vlad

0

指的是当前类的实例


0

这是一个代表类当前实例的变量。例如

class SampleClass {
public SampleClass(someclass obj) {
obj.sample = this;
}
}

在这个例子中,使用它来设置someclass对象的“sample”属性,将其设置为SampleClass的当前实例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接