【发布时间】:2023-01-08 00:38:55
【问题描述】:
我试图理解基本类型的装箱和测试的概念,尤其是元组。
我有两个来自外部 C# 库的对象,它们具有不同的具体类型但共享一个公共基类型:
let o1 = ConcreteType1() // has base type BaseType
let o2 = ConcreteType2() // also has base type BaseType
如果o1和o2都派生自BaseType,我必须执行一些特殊的比较逻辑,所以我想测试元组(o1, o2)的元素是否都具有基类型BaseType。
基于answers to this question,我想我必须装箱每个元素类型的分别地并对单个元素执行类型测试,以便考虑基本类型:
match box o1, box o2 with
| (:? BaseType), (:? BaseType) -> // special logic with o1, o2
| _ -> // nope, some other behavior
我的理解是,简单地装箱元组本身不会将单个元素向上转换为 obj,因此对它们的基本类型的测试将不起作用:
match box (o1, o2) with
| :? (BaseType * BaseType) -> // never hit, because elements are not upcast to obj
| _ -> // ...
这是对观察到的行为的正确解释,还是涉及其他机制?
【问题讨论】:
标签: f# boxing type-testing