如何在F#中将CultureInfo赋予TryParse方法

问题描述

|| 在F#中,我使用
let foo str =
    match Decimal.TryParse str with
    | (true,result) -> Some result
    | (false,_) -> None
它使用当前的系统区域性来解析字符串。但是我实际上想使用CultureInfo.InvariantCulture解析字符串。可以像上面这样的模式匹配方式完成吗?如果没有,最干净的方法是什么?     

解决方法

使用类似:
 let foo str =
     match System.Decimal.TryParse(str,NumberStyles.AllowDecimalPoint,CultureInfo.InvariantCulture) with
     | (true,result) -> Some result
     | (false,_) -> None 
    ,您需要使用将
NumberStyles
作为第二个参数并将
CultureInfo
作为第三个参数的重载。由于这是一个.NET方法,因此对参数进行了元组化(除了F#编译器将最后的
byref
参数转换为返回类型):
let foo str =
  match Decimal.TryParse(str,NumberStyles.None,CultureInfo.InvariantCulture) with
  | (true,result) -> Some result
  | (false,_) -> None
该方法的类型签名(如Visual Studio工具提示中所示)为:   Decimal.TryParse(s:string,style:NumberStyles,provider:IFormatProvider,result:byref ):布尔 当使用带有模式匹配的方法时,编译器将所有参数
byref
从参数列表的末尾转换为返回的元组的(最后)元素,但是它将参数保留为元组,因此您必须使用
TryParse(foo,bar)
调用方法符号。     ,使用TryParse方法的另一个重载
open System
open System.Globalization
let parse s = 
    match Decimal.TryParse(s,NumberStyles.Number,CultureInfo.InvariantCulture) with
    | true,v -> Some v
    | false,_ -> None
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...