【发布时间】:2010-09-14 21:12:27
【问题描述】:
我目前正在构建一个半复杂的计算器,它基本上是从我提供的 Excel 电子表格转换而来的。
我已经完成了大部分工作,但 Excel 电子表格中有一部分在 6 行和 7 列之间发生了多次计算,但问题是这些计算没有按任何特定顺序进行。
例如,Row0[Column1] 是使用 (Row2[Column4] * Row2[Column5]) 计算的,Row1[Column4] 是使用 (Row4[Column2] / Row5[Column1]) 计算的等等......你明白了。
我曾考虑过使用二维数组,但担心这些值会按特定顺序计算,因此在达到它们时没有任何价值。据我所知,将首先计算 Row1,然后是 Row2、Row3 等。
所以,如果不为我的 excel 电子表格中的每个单元格创建一个变量(并对其进行适当的排序),有没有一种方法可以使用 C# 进行计算?
我非常感谢任何您认为可能的帮助、建议、指点 - 我很想听听!
EDIT 实现@dtb提供的Lazy类后,得到如下代码。这是我提供的 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.
谷歌搜索错误返回了一堆垃圾搜索类型的网站。
马尔科
【问题讨论】:
-
这是什么错误?编译器错误还是异常?您是否增强了 Lazy 类以进行循环依赖检测?因为您的定义中有一个: sr[1,5] 是根据 sr[2,5] 定义的,反之亦然。
-
嗨@dtb - 项目编译但我得到一个异常。我暂时使用.NET 4(直到我让它在原始类中工作)。顺便说一句,我不确定如何扩展循环依赖的类,这(相当)有点超出我的知识范围。
-
那么你刚刚遇到了.NET 4.0 Lazy 类的循环依赖检测。您可以通过将 valueCreated 设置为 1 before 调用 valueFactory,设置为 2,并在调用 Value 并且 valueCreated 为 1 时抛出异常来自己实现它...仔细检查是否真的有循环定义你的excel表。如果有,请使用 excel 公式发布一个新问题,并询问如何在 C# 中计算定点。但我怀疑你的代码中有错字。
-
我已经对代码进行了三次检查,这正是电子表格中的内容,所以这意味着我确实需要实现循环依赖?我要问一个新的问题吗?
-
如果存在循环依赖,那么我使用 Lazy 的方法不起作用。使用精确的 Excel 公式集提出一个新问题。包括“定点”一词和该问题的链接。 :-)
标签: c# excel multidimensional-array lazy-evaluation calculated-columns