2017-08-25 50 views
0

如何簡化對象初始值設定項內的條件語句,以便代碼更易讀?如果addNew爲true,則新項目被添加到字典中,否則它將只有一個項目。帶條件語句的對象初始值設定項

... 
var channel = new ChannelConf { 
Name = "Abc" 
Headers = !addNew ? new Dictionary<string, string> 
      { 
       [Constants.Key1] = Id 
      } 
      : new Dictionary<string, string> 
      { 
       [Constants.Key1] = Id, 
       [Constants.Key2] = Port 
      } 
} 
... 
+0

可能想用標籤標識語言。 –

+0

你可能會想到使用構造函數重載'new ChannelConf(bool addNew)' – ibubi

+0

* *不*使用initalizers中的條件? 'if(addNew){channel.Headers.Add(Constants.Key2,Port); }初始化後是一個巨大的改進。請記住,初始化器只是事後屬性分配的簡寫。你沒有得到獎勵在一個街區擠壓一切。 –

回答

1

你可以調用一個方法來初始化Headers

... 
new ChannelConf { 
Name = "Abc" 
Headers = GetNewDictionary(addNew) 
} 
... 

private Dictionary<string, string> GetNewDictionary(bool addNew) 
{ 
    Dictionary<string, string> output = new Dictionary<string, string> { [Constants.Key1] = Id }; 

    if (addNew) { output.Add(Constants.Key2, Port); } 

    return output; 
} 

或者,你可以離開它,它是這樣的,減少的行數:

... 
var channel = new ChannelConf { 
Name = "Abc" 
Headers = !addNew ? new Dictionary<string, string> { [Constants.Key1] = Id } 
      : new Dictionary<string, string> { [Constants.Key1] = Id, [Constants.Key2] = Port } 
} 
... 
0

我想通過參數化構造函數完成事情是一個好習慣。這可能是其他人使用的常見API,因此您可以很容易地記錄並且不必告訴消費者如何使用API​​。

public ChannelConf(bool addNew) 
{ 
    Headers = !addNew 
     ? new Dictionary<string, string> 
     { [Constants.Key1] = Id } 
     : new Dictionary<string, string> 
     { 
      [Constants.Key1] = Id, 
      [Constants.Key2] = Port 
     }; 
} 
相關問題