我继承了这个代码,它接受一个 IEnumerable 并对其执行一系列选择,然后在执行选择后尝试对剩余记录调用 Sum。代码如下:
var totalrecs = records.Select(row => new RowInfo(RowID = row.RowID, SomeData = row.SomeData})
.Select(ri => new {RowInfo = ri, XMLData = GetXMLFileForRecord(ri)})
.Select(data => ParseAndUpdateRecords(data.RowInfo, data.XmlData))
.Sum();
其中“记录”是一个 IEnumerable。
该错误是因为尝试将小数转换为长整数,并且在三个 Select 调用产生的迭代器上调用 Sum 时似乎发生了 StackTrace。
堆栈跟踪是:
Exception:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot implicitly convert type 'decimal' to 'long'. An explicit conversion exists (are you missing a cast?)
at CallSite.Target(Closure , CallSite , Object )
at RecordCapture.Controller.<CaptureAndUpdateRecords>b__10(Object row)
at System.Linq.Enumerable.<>c__DisplayClass12`3.<CombineSelectors>b__11(TSource x)
at System.Linq.Enumerable.<>c__DisplayClass12`3.<CombineSelectors>b__11(TSource x)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.Sum(IEnumerable`1 source)
at RecordCapture.Controller.CaptureAndUpdateRecords()
at RecordCapture.Controller.<Start>b__1()
StackTrace: at CallSite.Target(Closure , CallSite , Object )
at RosterCapture.Controller.<CaptureAndUpdateRosters>b__10(Object row)
at System.Linq.Enumerable.<>c__DisplayClass12`3.<CombineSelectors>b__11(TSource x)
at System.Linq.Enumerable.<>c__DisplayClass12`3.<CombineSelectors>b__11(TSource x)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.Sum(IEnumerable`1 source)
at RecordCapture.Controller.CaptureAndUpdateRecords()
at RecordCapture.Controller.<Start>b__1()
Selects 返回一个 Iterator,似乎没有任何方法可以准确计算 Selects 的结果。
有趣的是,如果 records 为空,调用 Sum 只会返回零并且不会引发错误。