[英]What is the difference between the override and new keywords in C#?
[英]c# What makes the difference between the two this keywords in the constructor below?
我不明白以下內容:在下面的代碼中,Visual Studio告訴我,我可以通過刪除構造函數中的第二個this
關鍵字來簡化我的代碼。
但是,為什么不能那么我弄死第一this
關鍵字? 這兩個變量都是在構造函數之外的類中聲明的,因此對於實例,兩者都將被“覆蓋”*。
如果我刪除這兩個this
關鍵字,然后VS會抱怨第一分配到同一個變量做出,而不是第二。 對我來說唯一明顯的區別是第二個變量是一個數組,但我不明白它會如何使它有所不同?
*我懷疑覆蓋不是這里正確的術語。
public class CelestialObject {
CelestialBody[] celestialBodies;
int celestialBodyCount;
public CelestialObject(int celestialBodyCount = 2) {
this.celestialBodyCount = celestialBodyCount;
this.celestialBodies = new CelestialBody[celestialBodyCount];
}
}
你不能做掉與第一this
關鍵字,因為你有相同的名稱作為您的字段參數celestialBodyCount
:
int celestialBodyCount; // The field
和
public CelestialObject(int celestialBodyCount = 2) { // The parameter.
需要this
關鍵字來指示該字段已分配給。 否則,該參數優先於該字段,如3.7.1名稱隱藏中所述 :
......實體的范圍可能包括引入包含同名實體的新申報空間的聲明。 此類聲明會導致原始實體隱藏。
然后3.7.1.1隱藏嵌套 :
由於在類或結構中嵌套類型以及作為參數和局部變量聲明的結果,在命名空間內嵌套命名空間或類型的結果可能會發生通過嵌套隱藏的名稱。
在這種情況下,參數celestialBodyCount
隱藏成員celestialBodyCount
。
當然,如果你刪除this
編譯器會幫忙,給你以下警告:
Assignment made to same variable; did you mean to assign something else?
此警告幾乎總是表示錯誤,應始終清理。
所不同的是,你有一個名為參數celestialBodyCount
-這意味着在構造函數中,標識符celestialBodyCount
指參數,因此訪問你有資格的字段中this
。
您沒有名為celestialBodies
的參數(或其他局部變量),因此該標識符已引用該字段,無需任何限定條件。
在此代碼中,沒有this
關鍵字:
public CelestialObject(int celestialBodyCount = 2)
{
celestialBodyCount = celestialBodyCount;
this.celestialBodies = new CelestialBody[celestialBodyCount];
}
Visual Studio說:“我很抱歉,但是沒有this
關鍵字,參數中有一個celestialBodyCount
,因此它將被分配給自己,因為它是具有該名稱的封閉匹配變量。你確定這是你的意思嗎?或者做你的意思是班級水平?“ Visual Studio對您很友好,但編譯器會繼續將參數中的celestialBodyCount
分配給它自己,並且不會將它分配給您的類級別字段。 所以要感謝Visual Studio,因為編譯器不會提醒您。
當你this.celestialBodyCount
Visual Studio知道你知道你正在將它分配給類級別字段。
對於this.celestialBodies
,沒有混淆,只有一個存在,所以它可以使用或不使用this
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.