代码示例:http://www.tryfsharp.org/create/dutts/Generics.fsx
我的 F# 中有一些映射代码,它采用 C# 对象并将其包装在可区分联合中。
module MyModule =
type MappedThings =
| DoThings of External.Things.DoThings
type MappedStuff =
| DoStuff of External.Stuff.DoStuff
由于我总是在可区分联合中使用与外部对象相同的名称,因此我想尝试使我的映射代码通用以实现可扩展性。这是我到目前为止所尝试过的:
let toDomain<'T> external : 'T =
let found = FSharpType.GetUnionCases(typeof<'T>) |> Seq.where (fun t -> t.Name = external.GetType().Name) |> Seq.head
FSharpValue.MakeUnion(found, [| box external |]) :?> 'T
我尝试像这样使用它:
let testThings = toDomain<MyModule.MappedThings> doExternalThings
let testStuff = toDomain<MyModule.MappedStuff> doExternalStuff
这对于第一次调用效果很好,但如果我尝试将它用于 MyModule.MappedStuff 类型,它会抱怨
This expression was expected to have type DoThings but here has type DoStuff
我尝试过使用静态解析的类型参数 ^T,但 typeof 抱怨。
我想如果我能以某种方式传递“类型”(如果这是正确的术语,例如 MyModule.Mapped)作为参数,我就可以让它工作,但我不知道如何以编程方式获取它。
有人可以帮忙吗?