也许这是一个愚蠢的问题,但是为什么来自unbox的返回值(在我的F#交互会话中)看起来是obj类型的,而不是具体的int类型?据我所知(试图应用来自C#的现有知识),如果它的类型是obj,那么它仍然是装箱的。示例如下:
> (unbox<int> >> box<int>) 42;;
val it : obj = 42
> 42;;
val it : int = 42发布于 2011-08-06 00:19:21
函数组合(f >> g) v的意思是g (f (v)),因此您实际上是在最后调用box<int> (而对unbox<int>的调用并不是必需的):
> box<int> (unbox<int> 42);;
val it : obj = 42
> box<int> 42;;
val it : obj = 42类型是box : 'T -> obj和unbox : obj -> 'T,因此函数在装箱类型(对象)和值类型(整型)之间进行转换。您可以调用unbox<int> 42,因为F#在调用函数时会自动插入从int到obj的转换。
发布于 2011-08-06 03:07:58
在相关的注释中:这种方法实际上非常有用。我用它来处理"the type of an object expression is equal to the initial type"行为。
let coerce value = (box >> unbox) value
type A = interface end
type B = interface end
let x =
{ new A
interface B }
let test (b:B) = printf "%A" b
test x //doesn't compile: x is type A (but still knows how to relax)
test (coerce x) //works just finehttps://stackoverflow.com/questions/6959374
复制相似问题