object - F# 中的内联 C# 对象创建

标签 object f# initialization

我正在尝试在某些 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
{
}

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

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

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

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

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

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

最佳答案

在 F# 中,您还可以 assign values to properties at initialization ,因此要在单个表达式中创建 Options 实例,您可以执行以下操作:

Options("Test", SomeProperty="SomeValue")

关于object - F# 中的内联 C# 对象创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63654100/

相关文章:

javascript - JavaScript 保证对象属性顺序吗?

node.js 需要在对象数组中使用引号吗?

winapi - f# 中的 Win32 api 调用错误 GetShortPathName

.net - F# 中的业务线应用程序多久会成为常态?

objective-c - Cocoa:从 AppDelegate.m 调用方法

c++ - 为什么结构内部的对象初始化不同?

javascript - 这怎么可能?访问对象变量

arrays - 在Powershell中将对象追加到数组

protected 方法的 F# 公共(public)覆盖

C:传递二维数组的一维会导致段错误