C#中的區域性變數衝突問題
阿新 • • 發佈:2020-01-07
一個變數在同一個作用域中不能夠宣告兩次,如下程式碼錯誤。
using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceConsoleApplication1 { class Program { static void Main(string[] args) { int a =123; int a =456; } } }
編譯錯誤如下:
嚴重性 |
程式碼 |
說明 |
專案 |
檔案 |
行 |
禁止顯示狀態 |
錯誤 |
CS0128 |
已在此範圍定義了名為“a”的區域性變數。 |
ConsoleApplication1 |
E:\01_workspace\02_programme_language\06_c#\2017\09\varConflict\ConsoleApplication1\ConsoleApplication1\Program.cs |
14 |
活動 |
警告 |
CS0219 |
變數“a”已被賦值,但從未使用過它的值 |
ConsoleApplication1 |
E:\01_workspace\02_programme_language\06_c#\2017\09\varConflict\ConsoleApplication1\ConsoleApplication1\Program.cs |
13 |
活動 |
警告 |
CS0219 |
變數“a”已被賦值,但從未使用過它的值 |
ConsoleApplication1 |
E:\01_workspace\02_programme_language\06_c#\2017\09\varConflict\ConsoleApplication1\ConsoleApplication1\Program.cs |
14 |
活動 |
但是,如下程式碼正常:
using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceConsoleApplication1 { class Program { static void Main(string[] args) { for (int a = 0;a < 10; a++) { Console.WriteLine(a); } for (int a = 0;a < 10; a++) { Console.WriteLine(a* 2); } } } }
編譯後執行結果:
原因:在第一個迴圈結束後,a的作用域已經跳出。
以上這篇C#中的區域性變數衝突問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。