2011-02-04 83 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());