C# 带有条件语句的对象初始值设定项

C# 带有条件语句的对象初始值设定项,c#,object,initializer,C#,Object,Initializer,如何简化对象初始值设定项中的条件语句,使代码更易于阅读?如果addNew为true,则将新项添加到字典中,否则它将只有一个项 ... var channel = new ChannelConf { Name = "Abc" Headers = !addNew ? new Dictionary<string, string> { [Constants.Key1] = Id } : new D

如何简化对象初始值设定项中的条件语句,使代码更易于阅读?如果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
          }
}
...
。。。
var channel=新ChannelConf{
Name=“Abc”
Headers=!addNew?新建字典
{ 
[Constants.Key1]=Id
}
:新字典
{
[Constants.Key1]=Id,
[Constants.Key2]=端口
}
}
...

您可以调用一个方法来初始化
标题

...
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;
}
。。。
新频道配置{
Name=“Abc”
Headers=GetNewDictionary(addNew)
}
...
私有字典GetNewDictionary(bool addNew)
{
字典输出=新字典{[Constants.Key1]=Id};
if(addNew){output.Add(Constants.Key2,Port);}
返回输出;
}
或者,您可以保持原样并减少行数:

...
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 }
}
...
。。。
var channel=新ChannelConf{
Name=“Abc”
Headers=!addNew?新字典{[Constants.Key1]=Id}
:新字典{[Constants.Key1]=Id[Constants.Key2]=Port}
}
...

我认为通过参数化构造函数来完成任务是一种很好的做法。它可能是其他人使用的常见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
        };
}
public ChannelConf(bool addNew)
{
Headers=!addNew
?新字典
{[Constants.Key1]=Id}
:新字典
{
[Constants.Key1]=Id,
[Constants.Key2]=端口
};
}

可能需要用标记标识语言。您可能会考虑使用构造函数重载
newchannelconf(bool addNew)
在初始化器中不使用条件行吗<代码>初始化后的if(addNew){channel.Headers.Add(Constants.Key2,Port);}是一个巨大的改进。记住,初始值设定项只是事后属性赋值的简写。你不会因为把所有东西都挤在一个街区里而得奖。