亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

動態訪問 for 循環中的變量名稱

動態訪問 for 循環中的變量名稱

C#
當年話下 2022-08-20 16:01:06
我創建了以下變量:count_1 count_2 count_3...現在我想檢查每個變量的條件。for(int j = 1; j <= 10; j++)    {        if ("count_" + j == 100)        {        ...        }     ...     }當然,這不起作用,因為“count_”+ j沒有轉換為變量。我該怎么做?
查看完整描述

1 回答

?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

您應該改用 a 或 (數組)。它們的存在正是為了這個目的。List<int>int[]


您可以在C#中執行“動態變量訪問”,但不建議(或者非常不鼓勵)這樣做,這將容易出錯。


使用數組的示例:


// definition of the array (and initialization with zeros)

int[] counts = new int[10];


// (...)


for(int j = 0; j < counts.Length ; j++)  // note that array indices start at 0, not 1.

{

    if (count[j] == 100)

    {

    ...

    }

 ...

 }

這是一個類似的版本,帶有:List<int>


Lists 更靈活,也稍微復雜一些(它們在執行期間的大小可能會發生變化,而數組是固定的,如果要更改大小,則必須重新創建一個全新的數組。


// definition of the list (and initialization with zeros)

List<int> counts = new List<int>(new int[10]);


// (...)


foreach (int count in counts)  // You can use foreach with the array example above as well, by the way.

{

    if (count == 100)

    {

    ...

    }

 ...

 }

對于測試,您可以初始化數組或列表的值,如下所示:


 int[] counts = new int[] { 23, 45, 100, 234, 56 };


 List<int> counts = new List<int> { 23, 45, 100, 234, 56 };

請注意,實際上,您可以同時對數組或 s 使用 or。這取決于您是否需要在某個地方跟蹤代碼的“索引”。forforeachList


如果您在使用或與數組一起使用時遇到問題,請告訴我。forListforeach


我記得當我第一次學習編程時,我想做一些像你count_1 count_2這樣的事情,等等......希望發現數組和列表的概念會改變我的潛在開發人員的想法,打開一個全新的領域。


我希望這將使您走上正確的軌道!


查看完整回答
反對 回復 2022-08-20
  • 1 回答
  • 0 關注
  • 79 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號