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這樣的事情,等等......希望發現數組和列表的概念會改變我的潛在開發人員的想法,打開一個全新的領域。
我希望這將使您走上正確的軌道!
- 1 回答
- 0 關注
- 79 瀏覽
添加回答
舉報