C#初始化器条件赋值

21
在C#的初始化器中,如果条件为false,我想要不设置属性。
类似于这样的代码:
ServerConnection serverConnection = new ServerConnection()  
{  
    ServerInstance = server,  
    LoginSecure = windowsAuthentication,  
    if (!windowsAuthentication)
    {
        Login = user,  
        Password = password  
    }
};

可以做到吗? 怎么做?

6个回答

38
这在初始化器中是不可能的,你需要编写单独的if语句。

或者,你可以尝试编写:

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

(根据你的ServerConnection类的工作方式)


那是我的错。当你的回答中只有“这是不可能的”时,我最初对你进行了负评,然后你添加了三元运算符。现在它显然被锁定了,我无法撤销投票。感谢服务器出问题! - Randolpho
1
@Randolpho:现在你可以撤回它。 - SLaks
@Randolpho...三元运算符,而不是第三运算符。 - Suncat2000
1
根据你的 ServerConnection 类的工作方式,如果你的构造函数分配了除 null 以外的默认属性值,并且你希望保留这些值用于 LoginPassword,那么这种方法可能行不通。 - xr280xr

16

有更好的方法,正如@SLaks在下面提到的那样。 - Mehdi Dehghani

6
我猜这样做是可行的,但这种逻辑有点违背使用初始化器的初衷。
ServerConnection serverConnection = new ServerConnection()  
{  
    ServerInstance = server,  
    LoginSecure = windowsAuthentication,  
    Login = windowsAuthentication ? null : user,
    Password = windowsAuthentication ? null :password
};

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,
    };
}

在我看来,这并不是很重要。除非你处理匿名类型,否则初始化语法只是一个可以使你的代码在某些情况下看起来更整洁的好用功能。如果为了初始化所有属性而牺牲可读性,我建议不要费力使用它。以下代码也没有问题:

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

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

4

注意:我不建议使用这种方法,但如果必须在初始化程序中执行(例如您正在使用LINQ或其他必须是单个语句的地方),则可以使用以下方法:

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

2
这个怎么样:
ServerConnection serverConnection = new ServerConnection();  

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接