因此,我有这段示例代码,我想在其中添加一个try-with块:
static member private SomeFunc
(someParam: list<DateTime*int>) =
let someLocalVar = helpers.someOtherFunc someParam
let theImportantLocalVar =
List.fold
helpers.someFoldFunc
([],someLocalVar.First())
someLocalVar.Tail
let first = fst theImportantLocalVar
let tail = someParam.Tail
helpers.someLastFunc(first,tail,theImportantLocalVar)我想要添加的try-with块应该只是包装对List.fold的调用,但是如果我只包装了该行,那么我以后就不能访问变量theImportantLocalVar。
现在,作为一种解决办法,我已经使用了try-with块包装整个函数体(除了关于分配someLocalVar的第一行之外),但我想避免这样做:
static member private SomeFunc
(someParam: list<DateTime*int>) =
let someLocalVar = helpers.someOtherFunc someParam
try
let theImportantLocalVar =
List.fold
helpers.someFoldFunc
([],someLocalVar.First())
someLocalVar.Tail
let first = fst theImportantLocalVar
let tail = someParam.Tail
helpers.someLastFunc(first,tail,theImportantLocalVar)
with
| BadData(_) -> raise (new
ArgumentException("output values can only increase: " + someLocalVar,
"someParam"))在C#中,我会用bool exception=false来解决这个问题,它会在catch块中转换成true (稍后在函数的第二部分中查询它),或者用null初始化theImportantLocalVar以便以后比较它;但是,在F#中,我需要mutable关键字,这是不鼓励的。
那么,如何在不使用可变变量的情况下做到这一点呢?
发布于 2014-05-13 17:02:51
try/with是一个表达式,所以您可以这样做:
let theImportantLocalVar =
try
List.fold
helpers.someFoldFunc
([],someLocalVar.First())
someLocalVar.Tail
with
| BadData(_) -> raise (new
ArgumentException("output values can only increase: " + someLocalVar,
"someParam"))https://stackoverflow.com/questions/23637347
复制相似问题