正如其他人提到的,這不能完全在初始化程序中完成。將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