C#にはそのような演算子が組み込まれていません。
私は他答えの1(間違いなくより明確に掲示例えばあるMath.Max
を使用しています1)を選択するだろうが、これはちょうど別の方法を示したものです。計算に明示的に型付けされた変数が必要であることは残念です。
Func<int,int> computation = (x) => x > 5 ? x : 5;
var item = computation(aclass.amethod());
インラインで、これはC#で醜いです。もちろん
var item = ((Func<int,int>)((x) => x > 5 ? x : 5))(aclass.amethod());
上記の両方本当にただに煮詰める:
var item = DoComputation(aclass.amethod());
をとC#は、おそらく、
:-)名前によるパスまたは使用しないことを利用拡張方法:
static class Ext {
public static TO Apply<TI,TO> (this TI obj, Func<TI,TO> fn) {
return fn(obj);
}
}
// note C# now lets us get away with no explicit Func<...> type
var item = Ext.Apply(aclass.amethod(), x => x > 5 ? x : 5);
// or as extension method -- imagine computation is as it was in the
// first example, or a compatible method group
var item = aclass.amethod().Apply(computation);
ハッピーコーディング。
* 3進演算子を意味しますか? :) – Mehrdad
ちょうどFYI、その演算子は*合体*演算子です。 SQLの 'COALESCE()'とよく似ています。 –
moo、それは正しいです、合体のための類似した.net関数はありますか?そしておそらくショートカット版ですか? –