这将起作用。
Action<int> ff = (1 == 2)
? (Action<int>)((int n) => Console.WriteLine("nope {0}", n))
: (Action<int>)((int n) => Console.WriteLine("nun {0}", n));
这里有两个问题
- 表达
- 三元运算符
1. 表达问题
编译器准确地告诉你出了什么问题 - 'Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'
。
这意味着您编写的是 lambda 表达式,结果变量也是 lambda 表达式。
lambda 表达式没有任何特定类型 - 它只是可转换为表达式树。
成员访问表达式(这是您尝试做的)仅在表单中可用
primary-expression . identifier type-argument-list(opt)
predefined-type . identifier type-argument-list(opt)
qualified-alias-member . identifier type-argument-list(opt)
...并且 lambda 表达式不是主要表达式。
2. 三元运算符的问题
如果我们这样做
bool? br = (1 == 2) ? true: null;
这会导致错误说与您的完全一样。'Type of conditional expression cannot be determined because there is no implicit conversion between 'bool' and '<null>'
但是如果我们这样做,错误就消失了
bool? br = (1 == 2) ? (bool?)true: (bool?)null;
一侧的铸造也将起作用
bool? br = (1 == 2) ? (bool?)true: null;
或者
bool? br = (1 == 2) ? true: (bool?)null;
对于您的情况
Action<int> ff = (1 == 2)
? (Action<int>)((int n) => Console.WriteLine("nope {0}", n))
: ((int n) => Console.WriteLine("nun {0}", n));
或者
Action<int> ff = (1 == 2)
? ((int n) => Console.WriteLine("nope {0}", n))
: (Action<int>)((int n) => Console.WriteLine("nun {0}", n));