F#:实现内联方法(在接口上)以避免使用真实类型
我正在尝试查看内联是否可以应用于已实现的方法,以便不必拼写出传入的特定类型。我已经使用一次性(不是继承/实现)方法来完成此操作,但也尝试使用接口来完成此操作。
type public IBookInteraction =
abstract inline CreateBook : 'a -> MethodResult<BasicBookModel>
type public BookInteraction(?userInteraction) =
interface IBookInteraction with
member inline x.CreateBook(bookModel) =
let userId = (^a : (member UserId : Int32 with get) (bookModel))
MethodResult<BasicBookModel>()
我猜有一种方法可以做到这一点,但它不适用于接口方法签名中的通用运算符(?)。
I'm trying to see if inline can be applied to an implemented method so that the specific type coming in doesn't have to be spelled out. I've done this with one off (Not inherited/implemented) methods, but trying to also do using an interface.
type public IBookInteraction =
abstract inline CreateBook : 'a -> MethodResult<BasicBookModel>
type public BookInteraction(?userInteraction) =
interface IBookInteraction with
member inline x.CreateBook(bookModel) =
let userId = (^a : (member UserId : Int32 with get) (bookModel))
MethodResult<BasicBookModel>()
I'm guessing there's a way to do this, but it doesn't work with a generic operator(?) in the interface method signature.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不相信可以有抽象的内联方法。即使可以,您的代码也无法工作,因为您的接口定义承诺用户可以使用任何
'a
调用它,但您的实现对'a
施加了静态成员约束code> - 在 F# 支持抽象内联方法的假设世界中,接口上方法的声明也需要包含约束。无论如何,要了解为什么 F# 不可能支持抽象内联方法,请考虑内联的含义:您编写的用于实现该方法的代码本质上将被复制并粘贴到调用站点中。但是,对于抽象方法,您不知道定义该方法的实现的具体类型,因此无法在编译时确定您应该内联哪些代码!
I don't believe it's possible to have abstract inline methods. Even if you could, your code wouldn't work, because your interface definition promises that users can call it with any
'a
, but your implementation places a static member constraint on'a
- in a hypothetical world where F# supported abstract inline methods, the declaration of the method on the interface would also need to include the constraint.In any case, to see why it's not possible for F# to support abstract inline methods, consider what
inline
means: the code that you write to implement the method will be essentially copied and pasted into the call site. However, with an abstract method, you don't know the concrete type that is defining the implementation of the method, so there's no way to figure out at compile time what code you're supposed to be inlining!我认为正确的答案是接口实现可能不会内联。我不确定为什么接口定义中允许它。
I think the correct answer is interface implementations may not be inlined. I'm not sure why it's allowed in the interface definition.