gpt4 book ai didi

c# - 公开要在构造函数中定义的类私有(private)字段

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:08 24 4
gpt4 key购买 nike

我有以下在其构造函数中采用配置的类:

public class Importer {

private ImporterConfiguration _configuration;

public Importer(String path, ImporterConfiguration configuration) {
_configuration = configuration;
}

}

我看到一些类可以这样使用:

Class class = new Class("path", x => {
x.ConfigurationProperty1 = 1;
x.ConfigurationProperty2 = 2;
});

如何允许以这种方式定义我的导入程序类 _configuration

最佳答案

您需要定义一个传递 Type ImporterConfiguration 的 Action,然后在构造函数本身内部创建对象,然后调用传递您创建的对象的上下文的操作。

例子:

public Importer(String path, Action<ImporterConfiguration> configuration) 
{
ImporterConfiguration importerConfiguration = new ImporterConfiguration();
configuration.Invoke(importerConfiguration);
_configuration = importerConfiguration;
}

用法:

Importer importer = new Importer("foo", x => { /*..*/ });

编辑(为什么我使用.Invoke):

您还可以创建基本配置,可以这么说,如果您对构造函数进行更改,将 Action 默认值传递为 null,并在操作上使用可为 null 的调用:

configuration?.Invoke(importerConfiguration);

这样,它将使用默认值创建 ImporterConfiguration,如果配置为 null,则它将使用“默认设置”

关于c# - 公开要在构造函数中定义的类私有(private)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59257669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com