为什么我不能以这种方式有条件地添加到列表中?

Mat*_*hew 2 c# operators

我很确定Java会让你这么做,但我可能错了.

List<string> myList = new List<string>();
bool istrue = false;
myList.Add(istrue ? "something" : void);
Run Code Online (Sandbox Code Playgroud)

Bol*_*ock 9

你不能那样用void.它不是表达式,它是方法sigs中使用的关键字.并且?:运算符要求所有操作数都是表达式.我甚至确信你不能用Java做到这一点.

为什么不是if语句?它使你想要做的事情变得更加清晰,正是因为void在这种情况下毫无意义.

  1. 只添加一些东西istrue,否则什么都不做:

    List<string> myList = new List<string>();
    bool istrue = false;
    
    if (istrue)
    {
        myList.Add("something");
    }
    
    Run Code Online (Sandbox Code Playgroud)

    在一行中:

    if (istrue) myList.Add("something");
    
    Run Code Online (Sandbox Code Playgroud)
  2. 添加一些if istrue,但是另外添加一个null值:

    List<string> myList = new List<string>();
    bool istrue = false;
    
    if (istrue)
    {
        myList.Add("something");
    }
    else
    { 
        myList.Add(null);
    }
    
    Run Code Online (Sandbox Code Playgroud)

    在一行中(null?:运营商合作):

    myList.Add(istrue ? "something" : null);
    
    Run Code Online (Sandbox Code Playgroud)

  • C#不是Python或Perl. (7认同)
  • 为if语句+1:if(istrue)myList.Add(“ something”); //简洁明了 (2认同)

小智 7

这个怎么样

public static void AddIf<T>(this List<T> list, bool flag, T obj)
{
    if (flag) { list.Add(obj); }
}
Run Code Online (Sandbox Code Playgroud)

只需传入 flag 和 item

myList.AddIf(true, item);
myList.AddIf(item!=item2, item2);
Run Code Online (Sandbox Code Playgroud)


Ode*_*ded 2

void仅在 (1) 作为方法的返回类型或 (2) 作为指针类型的基础类型时才合法。(感谢@Eric Lippert)。

这段代码甚至无法编译。

  • void 也是一种类型。它是一种只有 (1) 作为方法的返回类型或 (2) 作为指针类型的基础类型才合法的类型。因此,我必须说,这是一种非常糟糕的类型。但它是一种类型。是否是类型无关紧要;为了在条件表达式中使用,它必须是一个*作为操作数有效的表达式*,并且类型不是作为除“typeof”之外的任何内容的有效操作数的表达式。 (3认同)