请问在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;
}
请问在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;
}
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);
}
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
来引用它。
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;
}
}
this
。但对于 OP 的示例,使用 this
是强制性的。 - Vlad指的是当前类的实例
这是一个代表类当前实例的变量。例如
class SampleClass {
public SampleClass(someclass obj) {
obj.sample = this;
}
}
this
关键字指的是当前类的实例。” - VladMSDN
(因此指向那里是一个好主意)。其次,OP已经给出了上下文。在我看来,这是一个有效的问题。 - keyboardPthis
的参考资料:c# this
返回了很多好的结果(包括MSDN)。 - Chris Walsh