C#初始化条件赋值

在ac#initialiser中,如果条件为false,我想不设置属性。

像这样的东西:

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

可以办到? 怎么样?

你不能这样做; C#初始值设定项是名称=值对的列表。 详情请见: http : //msdn.microsoft.com/en-us/library/ms364047(VS80).aspx

您需要将if块移动到以下行。

这在初始化器中是不可能的; 你需要做一个单独的if语句。

或者,您也可以写作

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

(取决于ServerConnection类的工作方式)

我怀疑这会起作用,但是这种方式使用逻辑会破坏使用初始化程序的目的。

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

注意:我不推荐这种方法,但是如果它必须在初始化程序中完成(即你使用LINQ或其他必须是单个语句的地方),你可以使用:

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

正如其他人提到的,这不能在初始化器中完成。 是否可以将null分配给属性而不是根本不设置它? 如果是这样,您可以使用其他人指出的方法。 这是一个可以实现您想要的并且仍然使用初始化器语法的替代方案:

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

在我看来,这不应该太重要。 除非您正在处理匿名类型,否则初始化器语法只是一个很好的function,可以使您的代码在某些情况下看起来更整洁。 我会说,如果它牺牲了可读性,请不要用它来初始化你的所有属性。 改为执行以下代码没有错:

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

这个怎么样:

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