C#初始化条件赋值

Pom*_*ber 14 c# initializer

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

像这样的东西:

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

可以办到?怎么样?

SLa*_*aks 31

这在初始化器中是不可能的; 你需要单独if声明.

或者,您也可以写作

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

(取决于你ServerConnection班级的工作方式)


Tim*_*son 12

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

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

  • 嗨,为什么要downvote?这些信息不正确吗? (3认同)

Jay*_*Jay 6

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

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


Dr.*_*ice 5

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

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

在我看来,这应该没有多大关系。除非您正在处理匿名类型,否则初始化语法只是一个很好的功能,可以使您的代码在某些情况下看起来更整洁。我想说,如果它牺牲了可读性,就不要特意使用它来初始化所有属性。改为执行以下代码没有任何问题:

ServerConnection serverConnection = new ServerConnection()  
{
    ServerInstance = server,
    LoginSecure = windowsAuthentication,
};

if (!windowsAuthentication)
{
    serverConnection.Login = user,
    serverConnection.Password = password
}
Run Code Online (Sandbox Code Playgroud)