2011-07-19 69 views
1

我拉着所有的先進功能,共同爲這一個,但沒有泛型或lambda表達式的工作非常多:幫助用C#lambda表達式

這是我要創建的方法的實例:

MyClass mc = null; 
int x = mc.TryGetOrDefault(z => z.This.That.TheOther); // z is a reference to mc 
// the code has not failed at this point and the value of x is 0 (int's default) 
// had mc and all of the properties expressed in the lambda expression been initialized 
// x would be equal to mc.This.That.TheOther's value 

這就是我已經得到,但我不知道如何處理這個表達式對象。

[enter image description here1

+0

呀,原來它是這裏的防火牆阻止它... ...衛生署我 –

+0

看到圖片 – DaveShaw

+0

MC爲空 - 我不知道你是什麼嘗試實現...在使用該表達式之前分配mc會發生什麼? – Yahia

回答

1

這是諸如此類的事情,你後?

public static TResult TryGetOrDefault<TSource, TResult>(this TSource obj, Func<TSource, TResult> expression) 
{ 
    if (obj == null) 
     return default(TResult); 

    try 
    { 
     return expression(obj); 
    } 
    catch(NullReferenceException) 
    { 
     return default(TResult); 
    } 
} 
+0

這樣做。謝謝。 –

+0

還有一些想法在這裏:http://stackoverflow.com/questions/4958133/null-coalescing-within-an-invocation-chain – DaveShaw

0

你正在嘗試做什麼聽起來像Maybe

項目簡介:

也許或使用深表達式lambda表達式在C#IfNotNull

int? CityId= employee.Maybe(e=>e.Person.Address.City); 

更新:有一個關於如何最好地在this question完成這樣的事情更多的討論。

0

這裏是我後:

public static TResult TryGetOrDefault<TSource, TResult>(this TSource obj, Func<TSource, TResult> function, TResult defaultResult = default(TResult)) 
    { 
     try 
     { 
      defaultResult = function(obj); 
     } 
     catch (NullReferenceException) { } 
     return defaultResult; 
    } 
+0

請不要吞下異常! –

+0

我更新了,我認爲這樣更好。我聽到你在說什麼,我會在使用這種方法時小心。 –