如何在 F# 中定义编译时类型转换运算符?
鉴于:
let ab = ArgumentBlockSettingStore()
let a = ab :> ISettingStore
有没有办法定义前缀运算符 (~~)
以便这
let ab, a = ~~ArgumentBlockSettingStore() : _ * ISettingStore
成为可能?
Given:
let ab = ArgumentBlockSettingStore()
let a = ab :> ISettingStore
Is there a way to define a prefix operator (~~)
so that
let ab, a = ~~ArgumentBlockSettingStore() : _ * ISettingStore
becomes possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您遇到了评论中提到的编译器限制 - 您无法以完全通用且安全的方式编写
~~
运算符,这意味着它只允许转换为以下接口:论证实现。您可以定义一个将转换为任何其他类型的运算符,但这不太安全:我使用
内联
,因为该运算符非常简单,但它的工作方式与正常运营商。即使您在disposable
的类型注释中使用Random
,它也会编译,这有点不幸。I think you're hitting the compiler restrictions that you mentioned in the comment - you can't write the
~~
operator in a fully generic and safe way meaning that it will only allow casting to an interface that the argument implements. You can define an operator that will cast to any other type, but that's less safe:I used
inline
, because the operator is quite simple, but it works the same way with normal operators. This compiles even if you useRandom
in the type annotation fordisposable
, which is a bit unfortunate.