gpt4 book ai didi

.net - 错误 FS3039 : A direct reference to the generated type 'MyType' is not permitted

转载 作者:行者123 更新时间:2023-12-03 20:54:55 25 4
gpt4 key购买 nike

以下类型提供程序旨在创建 GeneratedNamespace.MyType它接受类型为 string 的静态参数并且只包含一个空的构造函数

namespace TypeProviderTest

open Microsoft.FSharp.Core.CompilerServices
open ProviderImplementation.ProvidedTypes
open System.Reflection
open System

[<TypeProvider>]
type MyTypeProvider(config:TypeProviderConfig) as this =
inherit TypeProviderForNamespaces()
let namespaceName="GeneratedNamespace"
let assembly = Assembly.LoadFrom(config.RuntimeAssembly)

//Provides definition, based on type parameters
let instantiationFunction typeName (typeParams:obj[]) =
match typeParams with
| [|:? string as param|] ->
//Creates an empty non-erased type
let definition = ProvidedTypeDefinition(
assembly,
namespaceName,
typeName,
Some typedefof<Object>,
IsErased = false
)

//Creates an empty constructor
let emptyCtor = ProvidedConstructor (parameters = [])
//Provides a call to base constructor
//(https://stackoverflow.com/questions/22520352/)
//Doesn't seem to help
let objCtor = typedefof<Object>.GetType().GetConstructor([||])
emptyCtor.BaseConstructorCall <- (fun _ -> objCtor,[])
emptyCtor.AddXmlDoc("Empty constructor test")

definition.AddMember(emptyCtor)
definition
| _ -> failwith "That was not supported"

let staticParams = [ProvidedStaticParameter("value",typedefof<string>)]
let t = ProvidedTypeDefinition(assembly,namespaceName,"MyType",Some typedefof<Object>)
do t.DefineStaticParameters(staticParams,instantiationFunction)


do this.AddNamespace(namespaceName,[t])
[<assembly:TypeProviderAssembly>]
do ()

当我尝试像这样使用它时
open System
open GeneratedNamespace
type X = MyType<"Abacaba">
[<EntryPoint>]
let main argv =
printfn "%A %A" typedefof<X> (new X())
Console.ReadLine() |> ignore
0

线路 type X = MyType<"Abacaba">产生错误

Error FS3039: A direct reference to the generated type 'MyType' is not permitted.



我添加了一个 base constructor call ,但它没有帮助

类型提供者是有意生成的

我的类型提供程序有错误吗?

最佳答案

我不确定如何使其完全工作,但我认为您收到错误的原因是参数化类型是删除类型(而提供静态参数后返回的类型不是删除类型)。

添加 IsErased = falset使错误消失:

let  staticParams = [ProvidedStaticParameter("value",typedefof<string>)] 
let t =
ProvidedTypeDefinition
(assembly,namespaceName,"MyType",Some typedefof<Object>,IsErased = false)
do t.DefineStaticParameters(staticParams,instantiationFunction)

有了这个,代码可以被编译,但尝试使用 new X() 创建一个实例。给出:

error FS0192: internal error: null: GetTRefType



所以,可能还有其他我遗漏的东西。也许它可以为您指明正确的方向!

关于.net - 错误 FS3039 : A direct reference to the generated type 'MyType' is not permitted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36793307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com