2010-07-12 70 views
8

在c#初始化程序中,如果条件为false,我不想设置属性。C#初始化条件赋值

事情是这样的:

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

它可以做什么? 如何?

回答

21

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

或者,你可以写

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

(取决于如何您ServerConnection类作品)

+0

为什么这个downvoted? – SLaks 2010-07-12 14:03:54

+0

那是我的错。当你的答案中的所有内容都是不可能的时候,我最初低估了你的意见,然后再添加你的高级操作员。现在它显然被锁定,我不能撤销投票。感谢服务器barfs! – Randolpho 2010-07-12 14:39:24

+1

@Randolpho:现在你可以取消它了。 – SLaks 2010-07-12 15:16:51

3

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

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

我怀疑这会起作用,但使用逻辑这种方式有损使用初始值设定项的目的。

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

正如其他人提到的,这不能完全在初始化程序中完成。将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 
} 
0

如何:

ServerConnection serverConnection = new ServerConnection(); 

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

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