我试图使用条件(三元)运算符为变量分配正确的lambda表达式,具体取决于条件,但我得到编译器错误:无法确定条件表达式的类型,因为'lambda表达式之间没有隐式转换'和'lambda表达'.我可以使用常规的if-else来解决这个问题,但是条件运算符对我来说更有意义(在这个上下文中),会使代码更简洁添加,至少,我想知道为什么它没有'工作.
// this code compiles, but is ugly! :)
Action<int> hh;
if (1 == 2) hh = (int n) => Console.WriteLine("nope {0}", n);
else hh = (int n) => Console.WriteLine("nun {0}", n);
// this does not compile
Action<int> ff = (1 == 2)
? (int n) => Console.WriteLine("nope {0}", n)
: (int n) => Console.WriteLine("nun {0}", n);
Run Code Online (Sandbox Code Playgroud)
Ric*_*lly 21
C#编译器尝试独立创建lambda,并且无法明确地确定类型.转换可以通知编译器使用哪种类型:
Action<int> ff = (1 == 2)
? (Action<int>)((int n) => Console.WriteLine("nope {0}", n))
: (Action<int>)((int n) => Console.WriteLine("nun {0}", n));
Run Code Online (Sandbox Code Playgroud)
Nik*_*wal 16
这会奏效.
Action<int> ff = (1 == 2)
? (Action<int>)((int n) => Console.WriteLine("nope {0}", n))
: (Action<int>)((int n) => Console.WriteLine("nun {0}", n));
Run Code Online (Sandbox Code Playgroud)
这里有两个问题
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)
Run Code Online (Sandbox Code Playgroud)
......并且lambda表达式不是主要表达式.
2.三元算子的问题
如果我们这样做
bool? br = (1 == 2) ? true: null;
Run Code Online (Sandbox Code Playgroud)
这导致错误说与你的完全一样. '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;
Run Code Online (Sandbox Code Playgroud)
一方的铸造也会奏效
bool? br = (1 == 2) ? (bool?)true: null;
Run Code Online (Sandbox Code Playgroud)
要么
bool? br = (1 == 2) ? true: (bool?)null;
Run Code Online (Sandbox Code Playgroud)
对于你的情况
Action<int> ff = (1 == 2)
? (Action<int>)((int n) => Console.WriteLine("nope {0}", n))
: ((int n) => Console.WriteLine("nun {0}", n));
Run Code Online (Sandbox Code Playgroud)
要么
Action<int> ff = (1 == 2)
? ((int n) => Console.WriteLine("nope {0}", n))
: (Action<int>)((int n) => Console.WriteLine("nun {0}", n));
Run Code Online (Sandbox Code Playgroud)
与其他人的答案基本相同,形式不同
Action<int> ff = (1 == 2)
? new Action<int>(n => Console.WriteLine("nope {0}", n))
: new Action<int>(n => Console.WriteLine("nun {0}", n));
Run Code Online (Sandbox Code Playgroud)
事实上,通过类型推断,您可以:
结果更加简洁.(我让你决定它是否更具可读性.)
var ff = condition
? (Action<int>)(n => Console.WriteLine("nope {0}", n))
: n => Console.WriteLine("nun {0}", n);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10163 次 |
| 最近记录: |