我很确定Java可以让你做到这一点,但我可能是错的。为什么我不能有条件地添加到列表中?
List<string> myList = new List<string>();
bool istrue = false;
myList.Add(istrue ? "something" : void);
我很确定Java可以让你做到这一点,但我可能是错的。为什么我不能有条件地添加到列表中?
List<string> myList = new List<string>();
bool istrue = false;
myList.Add(istrue ? "something" : void);
void
只有合法的(1),为返回类型的方法,或者(2)作为底层类型的指针类型。 (谢谢@Eric Lippert)。
这段代码甚至不会编译。
您不能像这样使用void
。这不是一个表达式,它是方法sigs中使用的关键字。而运算符?:
要求所有操作数都是表达式。我甚至可以确定你不能用Java来做到这一点。
为什么不是一个if语句?它使得你想要做的更清楚,因为void
在这种情况下是没有意义的。
只有istrue
添加一些东西,什么也不做,否则:
List<string> myList = new List<string>();
bool istrue = false;
if (istrue)
{
myList.Add("something");
}
在一个行:
if (istrue) myList.Add("something");
添加的东西,如果istrue
,但在其他方面增加一个空值:
List<string> myList = new List<string>();
bool istrue = false;
if (istrue)
{
myList.Add("something");
}
else
{
myList.Add(null);
}
在一个线(null
作品与?:
运营商):
myList.Add(istrue ? "something" : null);
我敢肯定,Java的不会让你这样做。 void
关键字表示方法不会返回任何内容。它与null
不一样,也不是一个空列表,也不能用它来表示“无所事事”,这就是你在这里所表达的意思。
你可能是对的,自从我使用Java以来已经有一段时间了。不过,我希望有一种方法可以“中止”表达。 – Matthew 2011-04-26 19:07:44
无效是不一样的NULL,
尝试
List<string> myList = new List<string>();
bool istrue = false;
myList.Add(istrue ? "something" : null);
可以
List<string> myList = new List<string>();
myList.Add(false ? "true" : "false");
将添加 “假” 到列表中。
我猜你上面的代码有一个问题,添加void作为字符串。
尝试
myList.Add(istrue ? "something" : string.empty);
编辑 如果你想只加时事是真的,然后就去做
if(isTrue)
myList.Add("something");
据我了解,你要有条件地添加元素作为对象初始化程序的一部分,而不是在随后的Adds中添加零碎。我在同一条船上。
这是顶级的谷歌的结果,所以为后人...
只要条件是集合中的每一个元素是相同的:
var myList = (from s in new List<string> { "alpha", string.Empty, "gamma" }
where !String.IsNullOrWhiteSpace(s)
select s);
为了解决这个问题,使用空而不是无效的。 – 2011-04-26 18:58:28
这不会是一样的行为。问题不是添加一个字符串或null,而是添加或不添加一个表达式添加到调用中。 – asawyer 2011-04-26 19:00:05
@Kyle,那实际上会增加null值。我想要一个“中止”选项。 – Matthew 2011-04-26 19:05:10