gpt4 book ai didi

C# 如何从公共(public)构造函数调用私有(private)构造函数

转载 作者:太空狗 更新时间:2023-10-30 00:52:46 25 4
gpt4 key购买 nike

我希望能够使用默认调用私有(private)构造函数的公共(public)构造函数实例化一个类,我认为它类似于下面的代码,但事实并非如此。

    public MySQLConnector()
: this MySQLConnector (ConfigurationManager.AppSettings["DBConnection"])
{
}

private MySQLConnector(string dbConnectionString)
{
//code
}

最佳答案

你已经快搞定了。只需使用 this(...),不带类名:

public MySQLConnector()
: this(ConfigurationManager.AppSettings["DBConnection"])
{
}

这记录在 Using Constructors (C# Programming Guide) 中:

A constructor can invoke another constructor in the same object by using the this keyword. Like base, this can be used with or without parameters, and any parameters in the constructor are available as parameters to this, or as part of an expression.

关于C# 如何从公共(public)构造函数调用私有(private)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19972046/

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