20

ac#initialiserで、条件がfalseの場合にプロパティを設定したくありません。

このようなもの:

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 に答える