2013-02-22 48 views
3

在構建過程中有沒有任何方式訪問匿名類型的成員?在施工期間訪問匿名類型的成員

例如

enumerable.select(i => new 
{ 
    a = CalculateValue(i.something), // <--Expensive Call 
    b = a + 5 // <-- This doesn't work but i wish it did 
} 

願意考慮替代方案來達到同樣的目標,這基本上是我伸出我的枚舉和投影的一部分,是一個昂貴的計算,其價值被多次使用,我不想重複它,也重複那個電話只是不感覺幹。

回答

6

這是不可能的,因爲新的匿名對象尚未實際分配,因此其屬性也不可用。您可以執行以下操作:

enumerable.select(i => 
    { 
     //use a temporary variable to store the calculated value 
     var temp = CalculateValue(i.something); 
     //use it to create the target object 
     return new 
     { 
      a = temp, 
      b = temp + 5 
     }; 
    }); 
+0

完美,非常感謝 – 2013-02-22 05:16:08