所以我有這個在我的C#的lib:動態關鍵字啓用「也許」monad?
public static TOut IfNotNull<TIn, TOut>
(this TIn instance, Func<TIn, TOut> func)
{
return instance == null ? default(TOut) : func(instance);
}
使用,如:
DateTime? expiration = promo.IfNotNull(p => p.TermsAndConditions.Expiration)
.IfNotNull(e => e.Date);
我一直令人頭大我的大腦試圖找出如何使用C#4 dynamic
關鍵字來啓用此語法代替:
DateTime? expiration = promoOffer.TermsAndConditions.Maybe()
.Expiration.Maybe()
.Date;
我有,我認爲工作了幾個例子,但它們打破了,當你開始鏈接的Maybe()
秒。
任何想法?
(我是在浪費我的時間嗎?是Maybe()
勝過IfNotNull()
)?
也許我已經得到了錯誤的想法,但不會在?操作員在這裏有用嗎? – spender 2010-10-07 00:41:27
動態變量無法看到我相信的擴展方法。 – 2010-10-07 00:44:59
我個人很喜歡'IfNotNull()'你現在有。由於你不能在擴展方法中使用'dynamic',所以我的感覺是代碼可能最終變得非常可怕。 – 2010-10-07 00:45:11