如何在fsharp的对象表达式中使用`member val`?

时间:2018-08-07 07:52:07

标签: f#

我有一个F#接口(由某种打字稿生成),看起来像这样:

type [<AllowNullLiteral>] AppOptions =
    abstract credential: Admin.Credential.Credential option with get, set
    abstract databaseAuthVariableOverride: Object option with get, set
    abstract databaseURL: string option with get, set
    abstract storageBucket: string option with get, set
    abstract projectId: string option with get, set

我认为创建该类型实例的最简单方法是创建一个简单的对象表达式,但是我无法使其正常工作。对象表达式中不允许member val吗?如果不是,最简单的方法是创建一个在所有属性上都具有getter和setter的接口的简单实例?这是我尝试的无效的方法:

let options = 
    { new Admin.AppOptions with
        member val credential: Admin.Credential.Credential option = None with get, set 
        member val databaseAuthVariableOverride: obj option = None with get, set 
        member val databaseURL: string option = None with get, set 
        member val databaseURL: string option = None with get, set 
        member val projectId: string option = None with get, set 
    }      

1 个答案:

答案 0 :(得分:2)

我不认为var成员是在对象表达式规范中的,只允许使用如下所示的长格式属性:

let options =
    let mutable credential = None 
    let mutable databaseAuthVariableOverride = None
    let mutable databaseURL = None
    let mutable storageBucket = None
    let mutable projectId = None
    { new AppOptions with
        member x.credential with get() = credential and set v = credential <- v
        member x.databaseAuthVariableOverride with get() = databaseAuthVariableOverride and set v = databaseAuthVariableOverride <- v
        member x.databaseURL with get() = databaseURL and set v = databaseURL <- v
        member x.storageBucket with get() = storageBucket and set v = storageBucket <- v
        member x.projectId with get() = projectId and set v = projectId <- v
    } 

哪个会像这样由编译器来投影类似C#的代码:

[assembly: FSharpInterfaceDataVersion(2, 0, 0)]
[assembly: AssemblyVersion("0.0.0.0")]
[CompilationMapping(SourceConstructFlags.Module)]
public static class _
{
    [Serializable]
    [AllowNullLiteral]
    [CompilationMapping(SourceConstructFlags.ObjectType)]
    public interface AppOptions
    {
        override FSharpOption<object> credential
        {
            get;
            set;
        }

        override FSharpOption<object> databaseAuthVariableOverride
        {
            get;
            set;
        }

        override FSharpOption<string> databaseURL
        {
            get;
            set;
        }

        override FSharpOption<string> storageBucket
        {
            get;
            set;
        }

        override FSharpOption<string> projectId
        {
            get;
            set;
        }
    }

See sharplab

正常类型在这里可能更简洁:

    type t() = 
     interface AppOptions with
         member val credential = None with get, set
         member val databaseAuthVariableOverride = None with get, set 
         member val databaseURL = None with get, set 
         member val storageBucket = None with get, set 
         member val projectId = None with get, set