可能重複:
When do you use the 「this」 keyword?在哪裏以及何時使用 「this」 關鍵字
大家好,
我只是想知道何時何地使用關鍵字是必須的?因爲有時如果我不「這個」,甚至我刪除「這個」,程序運行良好。那麼如果你不使用它會發生什麼?或者如果你在錯誤的地方使用它。
一些明確的例子將appriciated。
可能重複:
When do you use the 「this」 keyword?在哪裏以及何時使用 「this」 關鍵字
大家好,
我只是想知道何時何地使用關鍵字是必須的?因爲有時如果我不「這個」,甚至我刪除「這個」,程序運行良好。那麼如果你不使用它會發生什麼?或者如果你在錯誤的地方使用它。
一些明確的例子將appriciated。
的this
關鍵字通常用於成員變量和局部變量之間的歧義:
...
{
int variable = 10;
this.variable = 1; // modifies a member variable.
variable = 1; // modifies the local variable.
}
....
其他用途的this
是到參考傳遞到當前對象,以便:
....
DoSomethingWithAnObject(this);
....
另一個用途(感謝HadleyHope)是爲了消除方法參數是什麼時候的屁股igned成員變量具有相同的名稱:
void Initialise(int variable)
{
this.variable = variable;
}
調用靜態成員時不能使用它。編譯器不會讓你。當你使用「this」時,你明確地調用當前實例。我喜歡用「this」作爲當前實例成員的前綴,即使這不是強制性的,只是爲了清晰起見。這樣我就區分了局部範圍變量和成員。
乾杯
你不必使用「this」關鍵字在你的成員方法時,它都會在這種情況下非常有用:
class human
{
private int age;
...
void func(int age)
{
this.age = age;
}
...
}
它可以解決你的年齡意識混亂
public class People{
private String name;
private int age;
public People(String name, int age){
this.name = name;
this.age = age; //use this to declare that the age is the field in People class
}
}
一種方法來使用它,希望它可以幫助你。
微軟推薦使用成員變量駝峯,即
public class MyClass
{
private int myInt;
private void SetMyInt(int myInt)
{
this.myInt = myInt;
}
}
所以,如果你沒有足夠的「這個」關鍵字,將有私有成員和參數之間的混淆。
就我個人而言,我更喜歡用下劃線前綴我的私人成員以避免這種混淆。
private int _myInt;
所以唯一的真正用途,我覺得它是對當前對象的引用傳遞到別的
MyStaticClass.MyStaticMethod(this);
的東西,當你有一個成員變量和局部變量您可以使用此在同一範圍內的同名 - 「這個」將明確你的意思。
考慮一下:
class Person
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public Person(string name)
{
this.name = name; // "this" is necessary here to disambiguate between the name passed in and the name field.
this.Name = name; // "this" is not necessary, as there is only one Name in scope.
Name = name; // See - works without "this".
}
}
我個人使用這個不管什麼時候訪問成員變量或方法。 99%的時間不是必需的,但我認爲它提高了清晰度,使代碼更具可讀性 - 這是一個值得輸入4個字符和一個點的額外努力的高質量。
這有點主觀,但如果您使用的是正確的命名約定(我使用_camelCase
作爲成員變量),您將永遠不需要使用this
。
除了此異常:=)
當你想從類的擴展方法是內部調用擴展方法:
public class HomeController : Controller
{
public ActionResult Index()
{
// won't work
return MyCustomResult();
}
public ActionResult List()
{
// will work
return this.MyCustomResult();
}
}
public static class MyExtensions
{
public static MyResult MyCustomResult(this Controller instance)
{
return new SomeResult(instance.ActionName);
}
}
同時用來分配方法的參數與成員變量一樣的名字。 – HadleyHope
我還補充說,有一個思想流派建議避免範圍變量衝突,因爲它可能導致潛在的混淆,因此需要使用「this」進行排序。我傾向於在嚴格的短期基礎上自己使用它 - 例如在構造函數中,當你要做的是寫「this.liveStatus = liveStatus」時,它是無害的 –
@Joel:完全同意! – Nick