[英]How to write this C# code in F#
I'm used to write code like this in C#: 我习惯在C#中编写这样的代码:
SomeObj obj;
try{
// this may throw SomeException
obj = GetSomeObj();
}catch(SomeException){
// Log error...
obj = GetSomeDefaultValue();
}
obj.DoSomething();
This is the way I translated it in F# (obj being a list): 这是我在F#中翻译它的方式(obj是一个列表):
let mutable obj = []
try
obj <- getSomeObj
with
| ex ->
// Log ex
obj <- getSomeDefaultValue
doSomething obj
Is there any way to do this in F# without using a mutable variable? 有没有办法在不使用可变变量的情况下在F#中执行此操作? Is there a more 'elegant' way to handle this situation in F#?
是否有一种更“优雅”的方式来处理F#中的这种情况?
Thank you! 谢谢!
The F#-ish way is to return the same type of expression in both branches: F#-ish方式是在两个分支中返回相同类型的表达式:
let obj =
try
getSomeObj()
with
| ex ->
// Log ex
getSomeDefaultValue()
doSomething obj
In F#, you can handle exceptions using option
type. 在F#中,您可以使用
option
类型处理异常。 This is an advantage when there is no obvious default value, and the compiler forces you to handle exceptional cases. 当没有明显的默认值时,这是一个优势,编译器会强制您处理异常情况。
let objOpt =
try
Some(getSomeObj())
with
| ex ->
// Log ex
None
match objOpt with
| Some obj -> doSomething obj
| None -> (* Do something else *)
Wrapping this logic in functions... 在函数中包含这个逻辑......
let attempt f = try Some(f()) with _ -> None
let orElse f = function None -> f() | Some x -> x
...it could be: ...它可能是:
attempt getSomeObj |> orElse getSomeDefaultValue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.