2013-05-02 76 views
0

我目前正在測試將用戶的聯繫人詳細信息存儲在文件中的應用程序。該信息也作爲主要方法存儲在本地壓縮數據庫中 - 將這些信息存儲在此文件中是備份以防這些細節丟失。StreamReader.ReadLine()發生意外的結果

我用於測試的文件有我的個人數據,所以我希望你明白我用佔位符替換了行!這個文件的結構如下(減去第一行):

下面,我有一些代碼,讀取該文件,並存儲每行的變量。該文件的結構不會改變,因此,非常簡單的代碼:

public static bool RestoreBusinessTable(out string title, out string busName, out string mobileNumber, out string firstName, out string lastName) 
     {  
      string email = "", referral = "", contactNo, addressLine1 = "", addressLine2 = "", city = "", postcode = "", country = "", district = ""; 
      busName = null; 
      mobileNumber = null; 
      firstName = null; 
      lastName = null; 
      title = null; 

      try 
      { 
       if (!File.Exists(fileName)) 
        return false; 
       StreamReader sr = new StreamReader(fileName); 
       string work; 
       work = sr.ReadLine(); // Empty line 
       work = sr.ReadLine(); // Empty line 
       busName = sr.ReadLine(); 
       title = sr.ReadLine(); 
       firstName = sr.ReadLine(); 
       lastName = sr.ReadLine(); 
       email = sr.ReadLine(); 
       referral = sr.ReadLine(); 
       addressLine1 = sr.ReadLine(); 
       addressLine2 = sr.ReadLine(); 
       city = sr.ReadLine(); 
       postcode = sr.ReadLine(); 
       country = sr.ReadLine(); 
       work = sr.ReadLine(); // Empty line 
       work = sr.ReadLine(); // Empty line 
       contactNo = sr.ReadLine(); 
       district = sr.ReadLine(); 
       mobileNumber = sr.ReadLine(); 
       sr.Close(); 
       // Add to database here 
       return true; 
      } 
      catch 
      { 
       return false; 
      } 
     } 

運行此代碼,我注意到busNametitlefirstNamelastName中全部爲07777123456值。數據看起來像這樣:

07777123456 
07777123456 
07777123456 
07777123456 
[email protected] 

Address Line 1 
Address Line 2 
City 
Postcode 
Country 




07777123456 

我沒有任何異步進程或線程同時寫入文件。任何人都可以對這裏發生的事情有所瞭解,以及爲什麼前四行會顯示爲手機號碼?要做到這一點

+2

你說什麼不能使用你發佈的代碼發生。你如何調用這些代碼以及如何打印這些變量?也可以嘗試使用數據傳輸對象,而不是無數'out'參數。 – CodeCaster 2013-05-02 13:15:29

+2

看起來像你一再覆蓋'工作'。它只會將您分配給它的最後一個值。 – RichardTowers 2013-05-02 13:17:09

+0

哦,對不起,這不是你的'out'puts之一。 – RichardTowers 2013-05-02 13:18:19

回答

5

的一種方式將是調用代碼來提供相同的變量/字段的地址的各種out參數:

string tmp; 
RestoreBusinessTable(out tmp, out tmp, out tmp, ...); 

這裏相同的地址在每個位置通過,所以不管是否您的代碼分配到title,busName等,它是寫入相同的實際位置

由於mobileNumber最後被賦值,因此爲移動號碼指定的值將是所有值的值。

這裏的關鍵點在於titlebusName等不是每一個參考爲一個字符串 - 因爲out的(或ref,同樣)它們各爲參照參考爲一個字符串

+0

直到你寫下「他們每個都是對一個字符串引用的引用」,我才真正關注你。「 - 突然間,這個問題突然讓我很清楚。謝謝! – 2013-05-02 13:24:03