C#中的局部變量沖突問題
一個(gè)變量在同一個(gè)作用域中不能夠聲明兩次,如下代碼錯(cuò)誤。
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;
}
}
}
編譯錯(cuò)誤如下:
|
嚴(yán)重性 |
代碼 |
說明 |
項(xiàng)目 |
文件 |
行 |
禁止顯示狀態(tài) |
|
錯(cuò)誤 |
CS0128 |
已在此范圍定義了名為“a”的局部變量。 |
ConsoleApplication1 |
E:\01_workspace\02_programme_language\06_c#\2017\09\varConflict\ConsoleApplication1\ConsoleApplication1\Program.cs |
14 |
活動(dòng) |
|
警告 |
CS0219 |
變量“a”已被賦值,但從未使用過它的值 |
ConsoleApplication1 |
E:\01_workspace\02_programme_language\06_c#\2017\09\varConflict\ConsoleApplication1\ConsoleApplication1\Program.cs |
13 |
活動(dòng) |
|
警告 |
CS0219 |
變量“a”已被賦值,但從未使用過它的值 |
ConsoleApplication1 |
E:\01_workspace\02_programme_language\06_c#\2017\09\varConflict\ConsoleApplication1\ConsoleApplication1\Program.cs |
14 |
活動(dòng) |
但是,如下代碼正常:
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);
}
}
}
}
編譯后執(zhí)行結(jié)果:

原因:在第一個(gè)循環(huán)結(jié)束后,a的作用域已經(jīng)跳出。
以上這篇C#中的局部變量沖突問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決C#中取消方向鍵對(duì)控件焦點(diǎn)控制的實(shí)現(xiàn)方法
本篇文章是對(duì)C#中取消方向鍵對(duì)控件焦點(diǎn)控制的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
解決C# 截取當(dāng)前程序窗口指定位置截圖的實(shí)現(xiàn)方法
本篇文章是對(duì)C#中截取當(dāng)前程序窗口指定位置截圖的實(shí)現(xiàn)方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C#獲取微信小程序的云數(shù)據(jù)庫中數(shù)據(jù)的示例代碼
本文主要介紹了C#獲取微信小程序的云數(shù)據(jù)庫中數(shù)據(jù)的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
DevExpress之ChartControl的SeriesTemplate實(shí)例
這篇文章主要介紹了DevExpress之ChartControl的SeriesTemplate用法實(shí)例,實(shí)現(xiàn)了餅狀Series百分比顯示的效果,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2014-10-10
C#實(shí)現(xiàn)將PPT轉(zhuǎn)換成HTML的方法
這篇文章主要介紹了C#實(shí)現(xiàn)將PPT轉(zhuǎn)換成HTML的方法,非常實(shí)用的功能,需要的朋友可以參考下2014-08-08

