gpt4 book ai didi

F# 强制重载 System.String.Format

转载 作者:行者123 更新时间:2023-12-01 08:04:45 25 4
gpt4 key购买 nike

我想使用 System.String.Format 格式化字符串它有 5 个重载:

String String.Format(String format , Object arg0 )
String String.Format(String format , Object arg0 , Object arg1 )
String String.Format(String format , Object arg0 , Object arg1 , Object arg2 )
String String.Format(String format , params Object[] args )
String String.Format(IFormatProvider provider , String format , params Object[] args )

我想像这样使用第四个重载(接受一组对象的重载):
let frm = "{0} - {1}"
let args = [| 1; 2 |]
System.String.Format(frm, args)

问题是 args 参数被解释为一个对象,因此调用了第一个重载。所以正确地我收到以下错误:
System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

有没有办法强制“正确”过载?

最佳答案

@John 答案的一个更优雅的变体是添加类型注释,以便编译器对数组的所有元素进行自动向上转换:

let frm = "{0} - {1}"
let args : obj [] = [| 1; 2 |]
System.String.Format(frm, args)

关于F# 强制重载 System.String.Format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17651006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com