所以我有这段代码示例,我想在其中添加一个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异常= false解决它,我会在catch块内变成true
(稍后在函数的第二部分查询它),或初始化{{1用null来比较它;但是,在F#中我需要theImportantLocalVar
关键字,这是不鼓励的。
那么如何在不使用可变变量的情况下做到这一点?
答案 0 :(得分:5)
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"))