20

在 ac# 初始化程序中,如果条件为假,我不想设置属性。

像这样的东西:

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

可以办到?如何?

4

6 回答 6

37

这在初始化程序中是不可能的;您需要单独if声明。

或者,您可以编写

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

(取决于你的ServerConnection班级如何运作)

于 2010-07-12T13:56:55.260 回答
15

你不能这样做;C# 初始值设定项是名称 = 值对的列表。有关详细信息,请参见此处:http: //msdn.microsoft.com/en-us/library/ms364047 (VS.80).aspx#cs3spec_topic5

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

于 2010-07-12T13:58:36.553 回答
6

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

ServerConnection serverConnection = new ServerConnection()  
{  
    ServerInstance = server,  
    LoginSecure = windowsAuthentication,  
    Login = windowsAuthentication ? null : user,
    Password = windowsAuthentication ? null :password
};
于 2010-07-12T13:58:37.333 回答
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
}
于 2010-07-12T14:16:18.590 回答
4

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

ServerConnection serverConnection = new ServerConnection()
{
    ServerInstance = server,  
    LoginSecure = windowsAuthentication,  
    Login = windowsAuthentication ? null : user,
    Password = windowsAuthentication ? null : password,   
}
于 2010-07-12T13:57:54.730 回答
2

这个怎么样:

ServerConnection serverConnection = new ServerConnection();  

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

if (!windowsAuthentication)
{
     serverConnection.Login = user;  
     serverConnection.Password = password;  
}
于 2017-08-18T07:57:07.363 回答