当用作通用接口参数时,为什么F#类型系统会对`unit`进行不同的处理? [英] Why is `unit` treated differently by the F# type system when used as a generic interface argument?

查看:92
本文介绍了当用作通用接口参数时,为什么F#类型系统会对`unit`进行不同的处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此界面:

type A<'a> =
    abstract X : 'a

让我们尝试使用int作为通用参数来实现它:

Let's try to implement it with int as a generic argument:

{ new A<int> with member this.X = 5 } // all is well

现在,让我们尝试unit作为参数:

Now, let's try unit for an argument:

// Compiler error: The member 'get_X : unit -> unit' does not have the correct type to override the corresponding abstract method.
{ new A<unit> with member this.X = () }

现在,如果我们定义了一个非泛型接口,那么一切也将正常运行:

Now, if we define a non-generic interface, everything also works well:

type A_int =
    abstract X : int

{ new A_int with member this.X = 5 } // works

type A_unit =
    abstract X : unit

{ new A_unit with member this.X = () } // works as well!

有什么我可以解决的问题吗?

Is there anything I can do to fix this problem?

推荐答案

在F#中,声明的返回类型为unit的抽象插槽在.NET IL中被编译为void的返回类型.相比之下,声明的返回类型为"T"的抽象槽在.NET IL中作为通用返回类型"T"进行编译,当由unit实例化T时,该抽象插槽将变为unit'.

In F#, an abstract slot with declared return type of unit gets compiled in .NET IL as a return type of void. In contrast, an abstract slot with declared return type of "T" gets compiled in .NET IL as a generic return type of "T", which when T is instantiated by unit becomes unit'.

请参阅:由于单元导致的F#接口继承失败

这篇关于当用作通用接口参数时,为什么F#类型系统会对`unit`进行不同的处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆