编译器不允许我使用三元运算符 return 对象

Compiler won't let me return object using ternary operator

我试图 return 数组“arr”的类型根据输入对象类型可以是 string[]string

public static object custom_return(object ob, string[] arr)
{
    return ob.GetType() == typeof(string) ? arr[0] : arr;
}

此代码无法编译,因为

ErrorCS0173 Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'string[]'

还分手了

    public static object custom_return(object ob, string[] arr)
    {
        if (ob.GetType() == typeof(string))
            return arr[0];
        else
            return arr;
    }

完全没有问题。为什么会这样?

来自MSDN

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

在您的情况下,stringstring[] 之间不存在隐式转换。

它不起作用,因为在三元运算符中,第二种类型必须(隐式或显式)匹配第一种(反之亦然)。

如果你这样做就有效:

return ob.GetType() == typeof(string) ? (object)arr[0] : arr;

因为 string[] 可以隐式转换为 object

相反的方法(string[]转换为object)也可以

三元运算符中两个成员之间的类型匹配在分配给结果之前进行评估,因此在您的情况下,它甚至在知道将要分配给 object 之前就给出了错误(所以它并不能推断这两种类型都应该能够隐式转换为 object

请注意(这是主观的和自以为是的),更喜欢在类型不匹配时使用if/else(我倾向于认为三元表达式作为 "single value")。对我来说,它使代码更具可读性并且更不容易出错。