使用单位作为类型参数和覆盖方法 [英] Using unit as Type Parameter and overriding methods
问题描述
我基本上是在问为什么以下几行代码不能编译:
I'm basically asking why the following lines of codes do not compile:
type IGenericType<'a> =
abstract member MyFunc : 'a -> 'a -> 'a
type Implementer() =
member x.Test () () = () // unit->unit->unit
interface IGenericType<unit> with
member x.MyFunc a b = b // FS0017
// member x.MyFunc () () = () // FS0017
只是想知道是否有一种方法可以使此工作按预期进行.我认为这是单元和泛型实现所必需的限制.
Just curious if there is a method to make this work as intended. I assume this is a limitation which has to to with the implementation of unit and generics.
我目前正在使用以下解决方法:
Im using the following workaround at the moment:
type Nothing =
| Nothing
type Implementer() =
interface IGenericType<Nothing> with
member x.MyFunc a b = b
希望有人可以对此行为有所了解.
Hope someone can bring some light over this behavior.
推荐答案
您猜对了.为了在.NET Framework中实现互操作性,F#编译器不会为unit
发出IL,而是将其替换为void
.
You guessed it right. For interoperability inside .NET framework, F# compiler doesn't emit IL for unit
but replace it by void
instead.
因此,您的通用接口可用于除unit
之外的任何类型.这似乎不是什么大问题;您的解决方法是解决此问题的不错方法.
Therefore, your generic interface works on any type but unit
. It doesn't seem to be a big problem; your workaround is a nice solution for this issue.
更详细的讨论可以在由于单元导致的F#接口继承失败中找到.
这篇关于使用单位作为类型参数和覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!