【发布时间】:2011-08-13 07:08:15
【问题描述】:
我很确定 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。它不是表达式,它是方法 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);
【讨论】:
void 仅在 (1) 作为方法的返回类型,或 (2) 作为指针类型的基础类型是合法的。 (感谢@Eric Lippert)。
这段代码甚至无法编译。
【讨论】:
这个怎么样
public static void AddIf<T>(this List<T> list, bool flag, T obj)
{
if (flag) { list.Add(obj); }
}
只需传入标志和项目
myList.AddIf(true, item);
myList.AddIf(item!=item2, item2);
【讨论】:
我很高兴这不起作用。如果我调用 .Add 我希望添加一些东西。如果这种类型的逻辑在你看不到的方法中怎么办?
myList.Add( aBlackBox.Method() );
是加了还是没加?!
【讨论】:
我很确定 Java 不会让你这样做。 void 关键字表示方法不返回任何内容。它和null不一样,也不和空列表一样,也不能用它来表示“什么都不做”,这就是你在这里的意思。
【讨论】:
void 不等于 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");
将“false”添加到列表中。
我猜你上面的代码在添加 void 作为字符串时遇到了问题。
试试
myList.Add(istrue ? "something" : string.empty);
编辑 如果您只想在某些事情为真时添加,那么就这样做
if(isTrue)
myList.Add("something");
【讨论】:
据我了解,您正在尝试有条件地添加元素作为对象初始化程序的一部分,而不是在后续添加中零碎添加。我在同一条船上。
这是 Google 的最高搜索结果,所以为了后代......
只要集合中每个元素的条件相同:
var myList = (from s in new List<string> { "alpha", string.Empty, "gamma" }
where !String.IsNullOrWhiteSpace(s)
select s);
【讨论】:
你可以创建你的扩展方法:
public static void Add<T>(this IList<T> source, T item, Func<bool> predicate)
{
if (predicate())
{
source.Add(item);
}
}
你这样使用它:
myList.Add("something", () => null != somethingElse);
【讨论】: