2017-05-04 100 views
3

我創建了Settings類,我用它編輯我的應用程序.ini文件。我Settings.ini文件看起來像這樣:返回空數組而不是null

[ACCOUNT] 
login=xyz 
password=xyz 
locations=1,2,5,8 

現在我越來越theese值是這樣的:

class Settings { 
    public static IniFile Config = new IniFile(Directory.GetCurrentDirectory() + @"\Settings.ini"); 
    public static string Login { get { return Config.Read("login", "ACCOUNT"); } set { Config.Write("login", "ACCOUNT"); } } 
    public static string Password { get { return Config.Read("password", "ACCOUNT"); } set { Config.Write("password", "ACCOUNT"); } } 
    public static int[] Locations { get { return Array.ConvertAll(Config.Read("locations", "ACCOUNT").Split(','), s => int.Parse(s)); } set { Config.Write("locations", "ACCOUNT"); } } 
} 

的問題是,當我Settings.ini文件都有空的位置:

locations= 

我變量Settings.Locations返回null而不是空數組。我試過這樣做:

public static int[] Locations 
{ 
    get { return new int[] {Array.ConvertAll(Config.Read("locations", "ACCOUNT").Split(','), s => int.Parse(s))}; } 
    set { Config.Write("locations", "ACCOUNT"); } 
} 

但是,這只是不工作。我不能將int []轉換爲int。你有什麼想法,我怎樣才能返回空陣列?

+0

我不明白,'Config.Read( 「位置」, 「帳戶」)'如果沒有位置返回null?因爲'Locations'屬性永遠不會返回null,因爲'Array.ConvertAll'永遠不會返回null。但是,如果'Config.Read'返回null'string.Split'會引發異常。 –

+0

你說得對。現在我注意到我得到'格式異常' –

+0

而不是'Array.ConvertAll',您應該使用循環和'int.TryParse'來嘗試解析每個令牌。那麼你可以處理無效輸入 –

回答

7

可以明確做這樣的:

public static int[] Locations 
{ 
    get 
    { 
     string locations = Config.Read("locations", "ACCOUNT"); 
     if (locations == null) 
     { 
      return new int[0]; 
     } 
     return locations 
       .Split(',')   // split the locations separated by a comma 
       .Select(int.Parse) // transform each string into the corresponding integer 
       .ToArray();   // put the resulting sequence (IEnumerable<int>) into an array of integers 
    } 
    set 
    { 
     Config.Write("locations", "ACCOUNT"); 
    } 
} 
+0

我不得不改變爲:'if(string.IsNullOrEmpty(works)){'並且它像魅力一樣工作。謝謝 :) –

5

首先,你對一行的干擾過多,所以它很難閱讀,更不用說排除故障。你需要的是這樣的:

public static int[] Locations 
{ 
    get 
    { 
     int[] values = Array.ConvertAll(Config.Read("locations", "ACCOUNT").Split(','), 
      s => int.Parse(s)) ?? new int[] { }; 
     return values; 
    } 
    set 
    { 
     Config.Write("locations", "ACCOUNT"); 
    } 
} 

通知我已經加入到?? new int[] { }首先聲明,這就是所謂the null coalescing operator結束。如果其他數組爲null,它將返回一個空數組。

這是一個偏好問題,但我將getter分成兩行的原因是我可以在返回之前調試和中斷以觀察返回值。您也可以在最後一個括號中打破,並觀察Locals窗口中的返回值。

+0

爲什麼聲明值而根本不使用它?除了丟失';' –

+0

我得到'格式異常',我didint注意到它。你的代碼也不起作用。 –