2011-06-07 110 views
4

任何人都可以在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; 
    } 
+5

爲什麼不能在[MSDN](http://msdn.microsoft.com/en-us/library/dk1507sz.aspx)查找? 「this'關鍵字指的是類的當前實例。」 – Vlad 2011-06-07 19:49:22

+4

vlad - 爲什麼不張貼在stackoverflow? – JonH 2011-06-07 19:50:06

+1

@Vlad - 這個問題對許多SO問題都有效。 SO的目的是成爲一個可以作爲參考的地方。首先,不是每個人都知道'MSDN'(所以指出他們有一個好主意)。其次,OP給出了背景。有效的問題IMO。 – keyboardP 2011-06-07 19:54:19

回答

14

this關鍵字是將類的當前實例的引用。

在你的榜樣,this是用來引用類Complex的當前實例並刪除在構造函數與類定義的public int real;的簽名int real之間的模糊性。

MSDN has some documentation在這個以及這是值得一試。

雖然與您的問題沒有直接關係,但this作爲擴展方法的第一個參數。它用作表示要使用實例的第一個參數。如果一個人想的方法在任何靜態類添加到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

0

這是一個表示類的當前實例的變量。例如

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

在此示例中,這用於將someclassobj上的「sample」屬性設置爲SampleClass的當前實例。

1

Nate和d_r_w有答案。我只是想在你的代碼中特別說明這一點。確實要求CLASS成員區分該職能的論點。所以,線

this.real = real 

裝置分配函數的值(在這種情況下,構造函數)的參數「真實」的類的成員「真正的」。一般來說,你最好使用情況下,也使區分更加清晰:

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 2011-06-07 20:04:10

1

當方法

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來引用它。