[英]Why doesn't this code compile?
我不明白為什么這樣的代碼無法構建:
if (SomeCondition) {
Boolean x = true;
} else {
Boolean x = false;
}
Debug.WriteLine(x); // Line where error occurs
它創建以下錯誤:
名稱“ x”在當前上下文中不存在
對我來說,在所有情況下都聲明x
,因為存在else
子句。 那么,為什么編譯器在Debug.WriteLine
行上不知道它?
x在寫入行超出范圍。
這是由於變量的作用域限定: { int x = 3; }
{ int x = 3; }
僅在塊內可見。 您應該將x
的聲明移到塊外:
Boolean x;
if (SomeCondition) {
x = true;
} else {
x = false;
}
Debug.WriteLine(x);
或者在上述情況下,甚至更好:
bool x = SomeCondition;
Debug.WriteLine(x);
變量僅在聲明該變量的塊中有效:
if (SomeCondition) {
Boolean x = true;
...
// end of life of Boolean x
} else {
Boolean x = false;
...
// end of life of Boolean x
}
當然,編譯器可能會認為
...但是他們為什么要這樣做? 僅為了涵蓋這一特殊情況,它使編譯器不必要地變得復雜。
因此,如果要在塊外部訪問x
,則需要在塊外部聲明它:
Boolean x;
if (SomeCondition) {
x = true;
} else {
x = false;
}
...
// end of life of Boolean x
當然,在這種特殊情況下,編寫起來要容易得多:
Boolean x = someCondition;
但是我想這只是一個虛構的例子來說明您的觀點。
Boolean x
的定義僅存在於所定義的范圍內。 我注意到以下范圍:
if (SomeCondition) { //new scope
Boolean x = true;
} // x is not defined after this point
else { //new scope
Boolean x = false;
} // x is not defined after this point
Debug.WriteLine(x); // Line where error occurs
最好的方法是在外部聲明變量:
Boolean x = false;
if (SomeCondition) {
x = true;
}
else {
x = false;
}
Debug.WriteLine(x);
在if-else塊中定義的變量在其外部將不可用。
您當然可以簡化為:
Boolean x = SomeCondition;
Debug.WriteLine(x); // Line where error occurs
但是如果不必在if語句之前聲明變量,則它仍在if語句之后的范圍內,如下所示:
Boolean x;
if (SomeCondition) {
x = true;
} else {
x = false;
}
Debug.WriteLine(x);
x
僅存在於其范圍內,該范圍是if
塊或else
塊, 而不是在if
語句完成之后。 盡管無論執行哪個塊都創建了它,但是在進入調試語句之前,它也已在該塊的末尾銷毀。
if (SomeCondition) {
Boolean x = true; <-- created here
} <-- destroyed here
else
{
Boolean x = false; <-- created here
} <-- destroyed here
Debug.WriteLine(x); <-- does not exist here
您可以將其更改為:
Boolean x;
if (SomeCondition) {
x = true;
} else {
x = false;
}
Debug.WriteLine(x);
這樣它就可以在if
之前存在並在之后進行。
C#不是PHP。 您必須在WriteLine的范圍內聲明它。
你最好寫:
Boolean x = SomeCondition;
Debug.WriteLine(x);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.