我有一个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
}
最佳答案
我不认为成员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
关于f# - 如何在fsharp的对象表达式中使用`member val`?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51721591/