在运行时创建F#记录或联合类型(不是其实例)

时间:2013-04-22 06:17:22

标签: f# f#-3.0

在运行时创建表示F#记录或联合的System.Type实例的最佳方法是什么?也就是说,我正在寻找记录和联合的等效FSharpType.MakeTupleType。

为了澄清,我对创建一个实例(即FSharpValue.MakeRecord或FSharpValue.MakeUnion)不感兴趣。

1 个答案:

答案 0 :(得分:2)

我不知道F#库中记录和联合的等效于FSharpType.MakeTupleType

在运行时创建类似结构的记录或联合类型的一种方法是使用Reflection.Emit。记录类型类似于密封类,而联合类型是一个抽象基类,每个案例都有密封类。

例如,以下函数生成最小F#记录类型:

open System
open System.Reflection
open System.Reflection.Emit

let MakeRecord(typeName:string, fields:(string * Type)[]) =
    let name = "GeneratedAssembly"
    let domain = AppDomain.CurrentDomain
    let assembly = domain.DefineDynamicAssembly(AssemblyName(name), AssemblyBuilderAccess.RunAndSave)
    let name = "GeneratedModule"
    let dm = assembly.DefineDynamicModule(name, name+".dll")
    let attributes = TypeAttributes.Public ||| TypeAttributes.Class ||| TypeAttributes.Sealed
    let typeBuilder = dm.DefineType(typeName, attributes)
    let con = typeof<CompilationMappingAttribute>.GetConstructor([|typeof<SourceConstructFlags>|])
    let customBuilder = CustomAttributeBuilder(con, [|SourceConstructFlags.RecordType|])
    typeBuilder.SetCustomAttribute(customBuilder)
    let makeField name t =
        let attributes = FieldAttributes.Assembly
        let fieldBuilder = typeBuilder.DefineField(name+"@", t, attributes)
        let attributes = PropertyAttributes.None
        let propertyBuilder = typeBuilder.DefineProperty(name, attributes, t, [||])
        let customBuilder = CustomAttributeBuilder(con, [|SourceConstructFlags.Field|])
        propertyBuilder.SetCustomAttribute(customBuilder)
        let attributes = MethodAttributes.Public ||| MethodAttributes.HideBySig ||| MethodAttributes.SpecialName
        let methodBuilder = typeBuilder.DefineMethod("get_"+name, attributes, t, [||])
        let il = methodBuilder.GetILGenerator()
        il.Emit(OpCodes.Ldarg_0)
        il.Emit(OpCodes.Ldfld, fieldBuilder)
        il.Emit(OpCodes.Ret)
        propertyBuilder.SetGetMethod(methodBuilder)
        fieldBuilder
    let types = fields |> Array.map snd
    let cb = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, types)
    let il = cb.GetILGenerator()
    il.Emit(OpCodes.Ldarg_0)
    il.Emit(OpCodes.Call, typeof<obj>.GetConstructor(Type.EmptyTypes))
    fields |> Array.iteri (fun i (name, t) -> 
        let paramName = name.Substring(0,1).ToLower()+name.Substring(1)
        let param = cb.DefineParameter(i+1, ParameterAttributes.In, paramName)
        let fieldBuilder = makeField name t
        il.Emit(OpCodes.Ldarg_0)
        il.Emit(OpCodes.Ldarg, param.Position)
        il.Emit(OpCodes.Stfld, fieldBuilder)
    )
    il.Emit(OpCodes.Ret)
    let t = typeBuilder.CreateType()
    assembly.Save("GeneratedModule.dll")
    t

let r = MakeRecord("MyRecord", [|"Alpha",typeof<int>;"Beta",typeof<string>|])

注意也可能需要生成Record类型的预期接口,即缺少IEquatable,IStructuralEquatable,IComparable和IStructuralComparable的实现。

<强>更新

扩展方法基于上面的代码示例的MakeTupleType和MakeUnionType现在可以在开源Fil(F#到IL编译器)项目(alpha)中使用。