在下面的代码片段中,我试图提取一个嵌套的元组中包含的recid,该元组构成了一个dict键。嵌套的元组格式为(Int32,(boolean,boolean)) -
我正在查找Int32项的值(它实际上是db记录的行ID )。
在下面的匹配代码中,我试图将recid添加到一个列表中,但首先我将对象转换为一个整数。
然而,这会产生以下错误-不确定为什么?
错误:此运行时强制或类型测试从类型'a‘到int32
涉及基于此程序点之前的信息的不确定类型。在某些类型上不允许运行时类型测试。还需要进一步的类型注释。这里引用的字典定义为:
// Create Dict
let rdict = new Dictionary<_,_>()
// Add elements
rdict.Add( (x.["PatientID"],(true,true) ),ldiff)
// Extract Dict items
let reclist = new ResizeArray<int32>()
for KeyValue(k,v) in rdict do
match k with
| ((recid,(true,true)) ->
printfn "Found a matching Record: %A " recid; // <- prints correct result
let n = (recid:?> int32) // <- coercion error
reclist.Add(n)发布于 2011-04-13 07:28:32
假设rdict是一个Dictionary<int*(bool*bool), _>,那么为了生成一个ResizeArray<int>,我建议:
let reclist =
(ResizeArray<_>(), rdict.Keys)
||> Seq.fold(fun list (id,_) -> list.Add id; list)另外,Dictionary<int*(bool*bool), _>给我的印象也很奇怪。为什么不是Dictionary<int*bool*bool, _>呢?也就是说,为什么要将bool对嵌套为第二个元组?如果您进行了此更改,则可以这样调用rdict.Add:
rdict.Add ((x.["PatientID"], true, true), ldiff)而reclist应该是:
let reclist =
(ResizeArray<_>(), rdict.Keys)
||> Seq.fold(fun list (id,_,_) -> list.Add id; list)编辑:在您的评论中,您提到希望基于Dictionary密钥中两个ResizeArray的不同组合来构建单独的bool。这里有一个关于这样做的想法:
let reclistOnlyA, reclistOnlyB, reclistBoth, reclistNeither =
((ResizeArray<_>(), ResizeArray<_>(), ResizeArray<_>(), ResizeArray<_>()), rdict.Keys)
||> Seq.fold(fun (a, b, both, neither as lists) (id, bools) ->
(match bools with
| true, false -> a
| false, true -> b
| true, true -> both
| false, false -> neither).Add id
lists)发布于 2011-04-14 14:03:22
为了完整性和将来的参考,我只是想在进一步测试的基础上发布我的结果。通过装箱/取消装箱,我能够成功地修改我之前发布的代码。
希望这能在将来对其他人有所帮助。
// Add initial value note the box call here
diff_dict.Add( (box x.["PatientID"],(true,true) ),ldiff)
let reclist = new ResizeArray<int32>()
for KeyValue(k,v) in rdict do
//printfn "Difference Dictionary - Key: %A; Value: %A; " k v
match k with
// extract the result - note the 'unbox' call
| (recid,(true,false)) -> let n:int32 = unbox recid
reclist.Add(n) https://stackoverflow.com/questions/5642628
复制相似问题