我目前正在構建一個半複雜的計算器,它基本上是從我提供的Excel電子表格轉換而來的。在C#中計算值的數組(從Excel轉換公式)
我已經掌握了大部分內容,但Excel電子表格中有一部分在6行和7列之間進行多次計算,但問題在於計算的發生並不是特定的順序。
因此,例如,Row0[Column1]
使用(Row2[Column4] * Row2[Column5])
和Row1[Column4]
使用(Row4[Column2]/Row5[Column1])
等計算計算..你的想法。
我想過使用二維數組,但恐怕值會按特定順序計算,因此在到達時沒有值。據我所知,ROW1將首先計算,然後行2,ROW3等
因此,沒有在我的Excel電子表格中每個單元創建一個變量(並適當地訂購吧) ,有沒有一種方法可以使用C#來計算?
我真的很感激任何幫助,建議,指針,無論你認爲可能 - 我很樂意聽到它!
編輯落實@dtb提供的懶惰下課後,我有下面的代碼。這是我提供的Excel電子表格內容的直接副本,包括指針&計算。
var sr = new Lazy<decimal>[6, 6];
sr[0, 0] = new Lazy<decimal>(() => sr[1, 0].Value - eNumber);
sr[0, 3] = new Lazy<decimal>(() => sr[0, 4].Value - sr[1, 0].Value - sr[1, 4].Value);
sr[0, 4] = new Lazy<decimal>(() => sr[0, 0].Value * edD);
sr[0, 5] = new Lazy<decimal>(() => sr[0, 0].Value);
sr[1, 0] = new Lazy<decimal>(() => sr[1, 5].Value);
sr[1, 4] = new Lazy<decimal>(() => sr[1, 0].Value * edD);
sr[1, 5] = new Lazy<decimal>(() => sr[2, 0].Value + sr[2, 5].Value);
sr[2, 0] = new Lazy<decimal>(() => eNumber * rRate);
sr[2, 4] = new Lazy<decimal>(() => sr[2, 0].Value * hdD);
sr[2, 5] = new Lazy<decimal>(() => sr[1, 5].Value);
sr[3, 1] = new Lazy<decimal>(() => sr[2, 5].Value);
sr[4, 2] = new Lazy<decimal>(() => eNumber * (ePc/100) + sr[2, 0].Value * (hlPc/100) - sr[3, 1].Value);
sr[5, 0] = new Lazy<decimal>(() => (sr[0, 0].Value + sr[1, 0].Value + sr[2, 0].Value)/ePerR);
sr[5, 2] = new Lazy<decimal>(() => sr[5, 0].Value/rLifecycle);
sr[5, 4] = new Lazy<decimal>(() => sr[5, 2].Value);
sr[5, 5] = new Lazy<decimal>(() => sr[5, 0].Value + sr[5, 2].Value - sr[5, 4].Value);
不過,我得到以下錯誤
ValueFactory attempted to access the Value property of this instance.
谷歌搜索錯誤返回一堆垃圾搜索型網站。
馬爾科
它是什麼樣的錯誤?編譯器錯誤或異常?你有沒有增強懶惰類來做循環依賴檢測?因爲你的定義中有一個:sr [1,5]用sr [2,5]定義,反之亦然。 – dtb 2010-09-15 00:28:07
嗨@dtb - 項目編譯,但我得到一個例外。我暫時使用了.NET 4(直到我在原始類中使用它)。順便說一句,我不確定如何擴展循環依賴的類,這(有點)超出了我的知識範圍。 – Marko 2010-09-15 00:32:52
然後你剛剛遇到.NET 4.0 Lazy類的循環依賴檢測。你可以通過在調用valueFactory之前將valueCreated設置爲1 *,在2之後通過設置valueCreated來實現它,並且在調用Value並且valueCreated爲1時拋出異常...仔細檢查Excel表單中是否真的存在循環定義。如果有,使用Excel公式發佈一個新問題,並詢問如何計算C#中的修復點。但是我懷疑你的代碼中存在拼寫錯誤。 – dtb 2010-09-15 00:45:07