在 F# 中内联 C# 对象创建

Loc*_*min 3 f# initialization object

我正在尝试在某些 F# 代码中与 C# 库互操作。将以下 C# 视为我正在使用的库(或跳过下面以查看我首先使用的实际库):

public class Options
{
    public Options(string name)
    {
        Name = name;
    }

    public string Name { get; }
    public string SomeProperty { get; set; }
}

public class ServiceBuilder
{
    public ServiceBuilder ApplyOptions(Options options)
    {
        //Apply Options in some way
        return this;
    }

    public TheService Build()
    {
        return new TheService();
    }
}

public class TheService
{
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试创建服务但保持流畅我有以下 F# 代码:

//Valid Approach but not inlined :(
let options = Options("Test")
options.SomeProperty <- "SomeValue"

let theService = 
    ServiceBuilder()
        .ApplyOptions(options)
        .Build();
Run Code Online (Sandbox Code Playgroud)
//Invalid Approach because SomeProperty is not virtual
let theService2 =
    ServiceBuilder()
        .ApplyOptions({
            new Options("Test2") with
                member _.SomeProperty = "SomeValue2"
        })
        .Build()
Run Code Online (Sandbox Code Playgroud)

有什么方法可以让我初始化我想在 F# 中尝试创建“theService2”的内联方式?在 C# 中,我只使用对象初始化器。F# 对象表达式已经过时,因为我无法控制类来使属性成为虚拟的。

对于我上面的 C# 所模拟的其他上下文,我特别尝试使用Serilog.Sinks.ElasticSearch nuget 包创建一个 Serilog Logger ,并在 F# 中大致执行以下代码(同样,如果可能,内联):

var loggerConfig = new LoggerConfiguration()
    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200") ){
         AutoRegisterTemplate = true,
         AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6
     });
Run Code Online (Sandbox Code Playgroud)

rob*_*ker 5

在 F# 中,您还可以在初始化时为属性赋值,因此要Options在单个表达式中创建实例,您可以执行以下操作:

Options("Test", SomeProperty="SomeValue")
Run Code Online (Sandbox Code Playgroud)