[英]Why does the array have more elements than I've defined?
所以,我有這個從INI文件中讀取的函數:
private void GetRigInfo()
{
RigInfo = new string[9];
var fileLocation = new string[2];
// The problem is that there's no telling where the hddrigsite.ini will be
stored. So, we have to find out where it is from the hddconfig.ini.
Log("Locating rig info");
// There's no telling if this will be on a 32 or 64 bit OS. Check for both
var rigInfoLocation = File.ReadAllLines(Environment.Is64BitOperatingSystem ?
@"C:\Program Files (x86)\HDD DrillView\hddconfig.ini" :
@"C:\Program Files\HDD DrillView\hddconfig.ini");
// This should get us the location of the rigsite info we need.
foreach (var s in rigInfoLocation.Where(s => s.Contains("data_dir")))
{
fileLocation = s.Split('=');
}
RigInfo = File.ReadAllLines(fileLocation[1] + "\\hddrigsite.ini");
Log("Rig info found");
}
現在,當我單步執行並到達函數中的最后一個Log()
並將鼠標懸停在RigInfo
,Visual Studio intellisense會向我顯示RigInfo{string[30]}
。 現在,我一直都明白= new string[9]
會創建一個9元素數組。 那為什么它允許有30個元素呢? 當我運行程序時,在這個數組中我沒有任何錯誤或任何錯誤。 事實上,它只是在整體方案中我需要它的方式。 感謝任何和所有幫助,了解它是如何以及為什么這樣。 還附有截圖,以獲得更好的視覺輔助
這里 :
RigInfo = File.ReadAllLines(fileLocation[1] + "\\hddrigsite.ini");
您正在為變量分配一個新值。在這種情況下,新的字符串[]。
因為您已在此行中更改了存儲在變量中的引用:
RigInfo = File.ReadAllLines(fileLocation[1] + "\\hddrigsite.ini");
你做的是你用一個全新的數組覆蓋你的9元素數組
RigInfo = File.ReadAllLines(fileLocation[1] + "\\hddrigsite.ini");
數組由ReadAllLines調用'重新定義'。 如果你已經通過索引將每一行分配給數組,那么你就會得到一個錯誤,但在這種情況下,你將指針從分配給你的數組的內存重定向,並將它指向ReadAllLines方法的輸出。
總是厭倦了Arr = somthing,因為這會改變數組引用本身。
您將File.ReadAllLines
分配給它,因此將分配新內存並且該數組是一個完整的新數組。 您基本上會覆蓋以前的作業。
RigInfo包含超過預期的9個元素,因為這一行:
RigInfo = File.ReadAllLines(fileLocation [1] +“\\ hddrigsite.ini”);
丟棄原始的RigInfo並創建一個新的字符串數組,其結果為File.ReadAllLines(fileLocation [1] +“\\ hddrigsite.ini”)
通過RigInfo = File.ReadAllLines(fileLocation[1] + "\\\\hddrigsite.ini");
,您正在分配一個由File.ReadAllLines(fileLocation[1] + "\\\\hddrigsite.ini");
生成的new array
File.ReadAllLines(fileLocation[1] + "\\\\hddrigsite.ini");
大小為30
到RigInfo
變量。
如果你這樣做
RigInfo [indx++] = one line at a time
然后,當您使用先前定義的數組時,它將在第9個元素后失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.