正如其他人提到的,这不能完全在初始化程序中完成。将 null 分配给属性而不是根本不设置它是否可以接受?如果是这样,您可以使用其他人指出的方法。这是完成您想要的并且仍然使用初始化器语法的替代方法:
ServerConnection serverConnection;
if (!windowsAuthentication)
{
serverConection = new ServerConnection()
{
ServerInstance = server,
LoginSecure = windowsAuthentication,
Login = user,
Password = password
};
}
else
{
serverConection = new ServerConnection()
{
ServerInstance = server,
LoginSecure = windowsAuthentication,
};
}
在我看来,这应该无关紧要。除非您正在处理匿名类型,否则初始化语法只是一个很好的功能,它可以使您的代码在某些情况下看起来更整洁。我想说,如果它牺牲了可读性,请不要使用它来初始化所有属性。改为执行以下代码没有任何问题:
ServerConnection serverConnection = new ServerConnection()
{
ServerInstance = server,
LoginSecure = windowsAuthentication,
};
if (!windowsAuthentication)
{
serverConnection.Login = user,
serverConnection.Password = password
}