我定义了以下隐式强制转换运算符:
let inline (!>) (x:^a) : ^b = ((^a or ^b) : (static member op_Implicit : ^a -> ^b) x)
这允许我使用json库,比如:
root.[objTypeKey] <- !> o.Desc.ObjType
其中根是一个JSONNode,它的索引器需要另一个JSONNode作为值。ObjType是一个字符串,在json库(用C#编写(中有一个从字符串到JSONNode的简单隐式转换运算符定义。
这整件事在.Net Framework上运行得很好,但将F#项目迁移到.Net Core 3.1(C#json库在.Net Standard 2.0上(时出现了新的冲突,字符串的新隐式强制转换运算符->ReadOnlySpan<char>
在保留最初的!>
运算符用法的同时,是否可以以某种方式规避这种情况?如果是,怎么做?我可以以某种方式禁止ReadOnlySpan<char>
干扰吗(在这个项目中不需要它(。
特定的编译器错误:
Error FS0041 No overloads match for method 'Item'.
Known types of arguments: string * ReadOnlySpan<char>
Available overloads:
- JSONNode.set_Item(aIndex: int, value: JSONNode) : unit // Argument 'aIndex' doesn't match
- JSONNode.set_Item(aKey: string, value: JSONNode) : unit // Argument 'value' doesn't match
这里有一个想法。您可以声明!>
的第二个非通用版本,它特定于JSONNode
:
module JSONNode =
let (!>) = JSONNode.op_Implicit
当模块打开时,F#编译器将更喜欢该版本。唯一的问题是它将阻止通用版本的使用。
用法:
module Example1 =
let node = JSONNode()
node.["key"] <- !> "value" // Error: ReadOnlySpan<char>
module Example2 =
open JSONNode
let node = JSONNode()
node.["key"] <- !> "value" // Success: JSONNode