在我们的一个项目中,我们有类似的东西:
DirectoryEntry directoryEntry;
if (user == "" && password == "")
directoryEntry = new DirectoryEntry(path);
else
directoryEntry = new DirectoryEntry(path, user, password);
我想知道是否有可能将此作为单行声明。我知道这两种方法的工作方式不同。但是,是否可以检查括号内的条件并让编译器决定采用哪种方法。我在考虑这样的事情:
DirectoryEntry directoryEntry =
new DirectoryEntry(path, (user == "" && password == "") ? user, password : [nothing]);
答案 0 :(得分:2)
为什么你不这样使用它?
DirectoryEntry directoryEntry = new DirectoryEntry(path);
if (user != "" && password != "")
{
directoryEntry.Username = user;
directoryEntry.Password = password;
}
答案 1 :(得分:1)
怎么样
DirectoryEntry directoryEntry = (user == "" && password == "") ? new DirectoryEntry(path) : new DirectoryEntry(path, user, password);
答案 2 :(得分:-2)
这会奏效。
DirectoryEntry directoryEntry = (user == "" && password == "") ? new DirectoryEntry(path) : new DirectoryEntry(path, user, password);