公开要在构造函数中定义的类私有字段

问题描述 投票:0回答:3

我有下面的类在其构造函数中进行配置:

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

c# c#-7.0
3个回答
2
投票

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

示例:

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

用法:

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

编辑(只添加要求的内容):

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

configuration?.Invoke(importerConfiguration);

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


1
投票

而不是接受配置的值,而是接受委托并执行它,并传递您现有的配置实例。

public class Importer {

    private ImporterConfiguration _configuration;

    public Importer(String path, Action<ImporterConfiguration> configurator) {
        var configuration = new ImporterConfiguration();
        configurator(configuration);
        _configuration = configuration;
    }
}

0
投票

可以使用两个可能不同的语法选项来配置此属性。如果要寻找一个特定的对象,我将在其中提供一些详细信息。

匿名对象语法

您是否可能会使用这种语法来指代为特定对象正确定义匿名对象?

var importer = new Importer("path", new ImporterConfiguration(){
   ConfigurationProperty1 = 1;
   ConfigurationProperty2 = 2;
});

此方法将起作用,并允许您在ImporterConfiguration对象中设置可公开访问的任何属性。

委托/动作语法

否则,如果要使用lambda样式语法,则需要将Action<ImporterConfiguration>定义为第二个参数,这将允许您传入委托以处理配置:

// Constructor that accepts a delegate for your configuration
public Importer(String path, Action<ImporterConfiguration> config) 
{ 
     // Create an instance
     var configuration = new ImporterConfiguration();
     configuration.Invoke(config);

     // Set your backing property
     _configuration = configuration;
}

这将被称为:

var importer = new Importer("path", x => { ... });

0
投票

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

示例:

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

用法:

Importer importer = new Importer("foo", x => { /*..*/ });
© www.soinside.com 2019 - 2024. All rights reserved.