C#中“this”的含义是什么
有人可以在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
类的当前实例,它消除了构造函数签名中public int real;
与public int real;
之间的歧义public int real;
在类定义中。
MSDN上有一些关于此的文档 ,值得一试。
虽然与您的问题没有直接关系,但另外还有一个用作扩展方法的第一个参数。 它用作表示要使用的实例的第一个参数。 如果想要在String class
添加一个方法,则可以在任何静态类中进行简单编写
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
this关键字引用类的当前实例,并且还用作扩展方法的第一个参数的修饰符。
这个(C#参考) – MSDN
C#关键字 – MSDN
Nate和d_r_w有答案。 我只想在你的代码中特别添加它。 在契约中引用CLASS的成员来区别于对FUNCTION的论证。 所以,这条线
this.real = real
表示将函数的值(在本例中为构造函数)参数’real’赋给类成员’real’。 一般来说,你也会使用案例来区分:
public struct Complex { public int Real; public int Imaginary; public Complex(int real, int imaginary) { this.Real = real; this.Imaginary = imaginary; } }
当身体的方法
public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; }
正在执行,它正在struct 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
引用了类的实例。
这是一个表示类的当前实例的变量。 例如
class SampleClass { public SampleClass(someclass obj) { obj.sample = this; } }
在此示例中,这用于将someclass obj上的“sample”属性设置为SampleClass的当前实例。
指当前的类实例
由于大多数答案提到“当前的class级实例”,新手可能难以理解“实例”这个词。 “类的当前实例”表示this.varible专门用于定义它的类中,而不是其他任何地方。 因此,如果变量名也出现在类之外,则开发人员不必担心多次使用相同变量名所带来的冲突/混淆。