2010-07-12 58 views
8

在c#初始化程序中,如果條件爲false,我不想設置屬性。C#初始化條件賦值

事情是這樣的:

ServerConnection serverConnection = new ServerConnection() 
{ 
    ServerInstance = server, 
    LoginSecure = windowsAuthentication, 
    if (!windowsAuthentication) 
    { 
     Login = user, 
     Password = password 
    } 
}; 

它可以做什麼? 如何?

回答

21

這在初始化程序中是不可能的;您需要製作單獨的if聲明。

或者,你可以寫

ServerConnection serverConnection = new ServerConnection() 
{ 
    ServerInstance = server, 
    LoginSecure = windowsAuthentication, 
    Login = windowsAuthentication ? null : user, 
    Password = windowsAuthentication ? null : password 
}; 

(取決於如何您ServerConnection類作品)

+0

爲什麼這個downvoted? – SLaks 2010-07-12 14:03:54

+0

那是我的錯。當你的答案中的所有內容都是不可能的時候,我最初低估了你的意見,然後再添加你的高級操作員。現在它顯然被鎖定,我不能撤銷投票。感謝服務器barfs! – Randolpho 2010-07-12 14:39:24

+1

@Randolpho:現在你可以取消它了。 – SLaks 2010-07-12 15:16:51

3

注:我不推薦這種方法,但如果它必須中完成一個初始化程序(即你使用的LINQ或其他地方,它必須是一個單一的陳述),你可以使用這個:

ServerConnection serverConnection = new ServerConnection() 
{ 
    ServerInstance = server, 
    LoginSecure = windowsAuthentication, 
    Login = windowsAuthentication ? null : user, 
    Password = windowsAuthentication ? null : password, 
} 
5

我懷疑這會起作用,但使用邏輯這種方式有損使用初始值設定項的目的。

ServerConnection serverConnection = new ServerConnection() 
{ 
    ServerInstance = server, 
    LoginSecure = windowsAuthentication, 
    Login = windowsAuthentication ? null : user, 
    Password = windowsAuthentication ? null :password 
}; 
3

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

如何:

ServerConnection serverConnection = new ServerConnection(); 

serverConnection.ServerInstance = server; 
serverConnection.LoginSecure = windowsAuthentication; 

if (!windowsAuthentication) 
{ 
    serverConnection.Login = user; 
    serverConnection.Password = password; 
}