inheritance - 从 F# 生成类型提供程序提供的类型继承

标签 inheritance f# type-providers

我有这个基本的生成 F# 类型提供程序

[<TypeProvider>]
type MyTypeProvider(config : TypeProviderConfig) as this = 
    inherit TypeProviderForNamespaces(config)

    let ns = "MyNamespace"
    let asm = Assembly.LoadFrom(config.RuntimeAssembly)

    let buildTypes (typeName:string) (args:obj[]) =
        let asm = ProvidedAssembly()
        let srvName = args.[0] :?> string
        ... omitted
        let provided = ProvidedTypeDefinition(asm, ns, typeName, Some typeof<MyRuntimeType>, hideObjectMethods = true, nonNullable = true, isErased = false)
        let ctor = ProvidedConstructor([], (fun _ -> <@@ MyRuntimeType() @@>))
        provided.AddMember(ctor)
        provided
    let parameters = 
        [ ProvidedStaticParameter("Host", typeof<string>, "") ]

    let provider = ProvidedTypeDefinition(asm, ns, "MyProvider", Some typeof<obj>, hideObjectMethods = true, nonNullable = true, isErased = false)
    do provider.DefineStaticParameters(parameters, buildTypes)
    do this.AddNamespace(ns, [provider])

[<assembly:TypeProviderAssembly()>]
do ()

在另一个项目中,我想不直接使用提供的类型,而是通过继承它:
type Provided = MyNamespace.MyProvider<"Host123">

type Derived() = 
    inherit Provided() //Cannot inherit a sealed type

但是我收到一条错误消息,指出所提供的类型是密封类,因此无法从中继承。

这是设计使然还是我错过了什么?

最佳答案

这是 F# 类型提供程序 SDK 中的默认行为。您可以在 ProvidedTypes.fs 中看到用于提供的类型定义的属性。在 ProvidedTypeDefinition类(围绕第 1241-1252 行):

    static let defaultAttributes isErased = 
        TypeAttributes.Public ||| 
        TypeAttributes.Class ||| 
        TypeAttributes.Sealed ||| 
        enum (if isErased then int32 TypeProviderTypeAttributes.IsErased else 0)

您可以通过显式传递 TypeAttributes 来覆盖它。对于构造函数的第五个参数(您必须使用接受所有参数的构造函数)。接您后 ... omitted部分,看起来像这样:
let derivableClassAttributes = TypeAttributes.Public ||| TypeAttributes.Class

let provided = 
    ProvidedTypeDefinition(false, 
                           TypeContainer.Namespace (K asm,ns), 
                           typeName, 
                           K (Some typeof<MyRuntimeType>), 
                           derivableClassAttributes, 
                           K None, 
                           [], 
                           None, 
                           None, 
                           K [||], 
                           true, 
                           true)

关于inheritance - 从 F# 生成类型提供程序提供的类型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51033847/

相关文章:

f# - 运算符优先级和关联

f# - 什么时候在F#中放入双分号?

f# - 如何创建可从 C# 使用的 F# 类型提供程序?

c++ - 以下操作安全吗?

python - 从python中的 `object`派生类

asp.net - F# 命名空间或模块 'XXXX' 未定义

f# - 提供类型的模式匹配

f# - ODataService 类型提供程序的可为空整数不存在属性 'HasValue'

java - 如何让 FillInTheBlank 打印问题(继承)

Scala:如何使子类(在其他实例上)可以访问 protected 方法?