正如其他人提到的,这不能完全在初始化程序中完成。将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
}
嗨,为什么downvote?这个信息不正确吗? – 2010-07-12 14:43:01
还有更好的办法,就像下面提到的@SLaks一样 – 2016-03-26 12:31:28