簡體   English   中英

多個字符串與字符串字典作為方法參數

[英]Multiple strings vs Dictionary of strings as method parameters

我有一些采用20個或更多字符串作為參數的方法。 我想知道哪種方法更好:將20個字符串參數傳遞給方法或將它們全部放入字典中,然后將其作為唯一參數傳遞。

多個字符串:

public Boolean isNice(string aux, string aux2, string aux3, string aux4, string aux5, string aux6, string aux7,
    string aux8, string aux9, string aux10, string aux11, string aux12, string aux13, string aux14, string aux15, string aux16)
{
    string foo1 = aux;
    string foo2 = aux2;
    // etc

    return true;
}

public void yeah()
{
    string aux = "whatever";
    string aux2 = "whatever2";
    // etc

    isNice(aux, aux2, ..., ..., ...);                 
}

字符串字典

public Boolean isNice(Dictionary<string, string> aux)
{
    string foo1 = aux["aux1"];
    string foo2 = aux["aux2"];
    // etc

    return true;
}

public void yeah()
{
    string aux = "whatever";
    string aux2 = "whatever2";
    // etc

    Dictionary<string, string> auxDict = new Dictionary<string,string>();

    auxDict.Add("key1", aux);
    auxDict.Add("key2", aux2);
    // etc

    isNice(auxDict);
}

我的問題是關於性能,可讀性和簡化代碼。

現在我正在使用多個字符串:我應該改用詞典嗎?

這取決於。 該功能正常工作是否需要所有20個參數?

如果是這樣,請創建一個可以傳遞所有20個值的數據類型,並傳入該數據類型的實例。 您可以創建幫助程序類以輕松初始化該類型的對象。 您可以輕松傳入該數據類型的新實例,並提供靈活的方式來初始化該類型:

isNice(new niceParams
   {
      aux1 = "Foo",
      aux2 = "Bar"
      // ...
   }
);

如果不是,請將可選參數放在簽名的末尾,並為其提供默認值。

public Boolean isNice(string req1, string req2, string optional1 = null)

這樣,您就有重載來確切指定要提供的值。

這樣做的另一個好處是您可以使用命名參數來調用該函數:

isNice(req1, req2, optional1: "Foo", optional15: "Bar");

話雖如此,我不會使用字典。 它迫使調用者理解簽名,並安全地完全破壞任何編譯器類型。 如果沒有提供所需的值怎么辦? 如果密鑰拼寫錯誤怎么辦? 現在必須在運行時完成所有這些檢查,從而導致只能在運行時捕獲的錯誤。 對我來說,這似乎是在自找麻煩。

主要區別在於,當您有20個string參數時,編譯器將確保所有這些參數都已顯式設置,即使它們設置為null 如果傳遞一個集合,編譯器將無法檢測到有人忘記設置aux17參數:使用基於字典的API的代碼將繼續編譯,因此您將被迫在運行時添加額外的檢查-時間。

例如,如果您的代碼不需要編譯器檢查就可以,因為所有string值都是可選的,則基於集合的方法更易於維護。

在實施更改之前,無法預測速度差異。 基於集合的方法將執行額外的內存分配,因此將消耗更多的CPU周期。 另一方面,差異可能太小而無法對程序的整體性能產生實際影響。

請注意,由於您的參數是統一命名的,因此似乎可以將它們放置在“平面”集合中,而不是字典中。 例如,您可以使API接受一個列表或字符串數​​組。 如果是數組,還可以使方法采用可變數量的參數,以便調用者可以使用舊語法來調用方法:

public bool isNice(params string[] args)

暫無
暫無

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

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