gpt4 book ai didi

C#构造函数在执行代码后调用构造函数

转载 作者:太空狗 更新时间:2023-10-29 22:10:23 26 4
gpt4 key购买 nike

我看过有关构造函数链的答案,但它们不适用于我的问题。

我有一个需要几个参数的构造函数:

public SerilogHelper(string conString, int minLevel)
{
var levelSwitch = new LoggingLevelSwitch();
levelSwitch.MinimumLevel = (Serilog.Events.LogEventLevel)(Convert.ToInt32(minLevel));

_logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitch)
.WriteTo.MSSqlServer(connectionString: conString,
tableName: "Logs",
autoCreateSqlTable: true)
.CreateLogger();
}

这个构造函数的一个特定客户端没有参数所需的值,所以我希望能够调用这个简单的构造函数,它将获得所需的值,然后调用第一个构造函数:

public SerilogHelper()
{
string minLevel = SSOSettingsFileManager.SSOSettingsFileReader.ReadString(
"LCC.Common", "serilog.level");
string conString = SSOSettingsFileManager.SSOSettingsFileReader.ReadString(
"LCC.Common", "serilog.connectionstring");

SerilogHelper(conString, minLevel);
}

问题是,我在调用第二个构造函数时出现红色波浪形消息 SerilogHelper is a 'type' but used like a 'variable'

最佳答案

为什么不直接添加这些参数呢?

// this assumes that SSOSettingsFileManager is static class
// this will automatically call these methods before passing
// values to another ( non parameterless ) constructor
public SerilogHelper()
: this (
SSOSettingsFileManager.SSOSettingsFileReader.ReadString(
"LCC.Common", "serilog.connectionstring"
),
SSOSettingsFileManager.SSOSettingsFileReader.ReadString(
"LCC.Common", "serilog.level"
)
)
{

}

// This will be called from default ( parameterless )
// constructor with values retrieved from methods
// called in previous constructor.
public SerilogHelper(string conString, int minLevel)
{
var levelSwitch = new LoggingLevelSwitch();
levelSwitch.MinimumLevel = (Serilog.Events.LogEventLevel)(Convert.ToInt32(minLevel));

_logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitch)
.WriteTo.MSSqlServer(connectionString: conString,
tableName: "Logs",
autoCreateSqlTable: true)
.CreateLogger();
}

Test online

关于C#构造函数在执行代码后调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44650429/

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