簡體   English   中英

返回空數組而不是 null

[英]Return empty array instead of null

我創建了Settings類,用於通過.ini文件編輯我的應用程序。 我的Settings.ini文件如下所示:

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

現在我得到這樣的值:

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。 你有什么想法我怎樣才能返回空數組?

您可以像這樣明確地執行此操作:

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");
    }
}

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

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[] { } ?? new int[] { }到第一個語句的末尾,稱為空合並運算符 如果另一個數組為null,它將返回一個空數組。

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

您希望避免零長度數組分配,不要使用:

return new int[0];

而是使用:

return Array.Empty<int>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM