これは機能します。
Action<int> ff = (1 == 2)
? (Action<int>)((int n) => Console.WriteLine("nope {0}", n))
: (Action<int>)((int n) => Console.WriteLine("nun {0}", n));
ここには2つの問題があります
- 表現
- 三項演算子
1.表現の問題
コンパイラは何が悪いのかを正確に教えてくれます- 'Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'
。
これは、あなたが書いたものがラムダ式であり、結果の変数もラムダ式であることを意味します。
ラムダ式には特定のタイプはありません。式ツリーに変換できるだけです。
メンバーアクセス式(これはあなたがやろうとしていることです)はフォームでのみ利用可能です
primary-expression . identifier type-argument-list(opt)
predefined-type . identifier type-argument-list(opt)
qualified-alias-member . identifier type-argument-list(opt)
...そしてラムダ式はプライマリ式ではありません。
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));