2011-02-04 140 views
20

.NET现在支持null coalescing operator单呼三元操作

var item = aVal ?? aDefaultVal; 

我可能会被忽视的东西很明显,但那里的三元运算符类似的东西,这样

var item = aclass.amethod() > 5 ? aclass.amethod() : 5; 

,而不是做止跌不需要拨打amethod()两次?

+7

你是指* ternary *运算符吗? :) – Mehrdad 2011-02-04 20:59:01

+1

只是FYI,该运营商是一个* coalesce *运营商。就像我们在SQL中看到的`COALESCE()'一样。 – 2011-02-04 21:04:17

+0

moo,这是正确的,是否有类似的.net功能coalesce?并优先考虑快捷版本? – 2011-02-06 14:18:01

回答

12

C#中没有这样的操作符。

虽然我选择其它答案之一(使用Math.Max可以说是更加清晰张贴的例子之一),这是在这里只是为了显示另一种方法。计算需要一个显式类型的变量是一个耻辱。

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); 

快乐编码。

26

如何:

var result = aclass.amethod(); 
var item = result > 5 ? result : 5; 

你只需要调用aclass.amethod()一次,然后。

28
var item = Math.Max(5, aclass.amethod());