一个类中的两个构造函数?

Bab*_*Bst -2 c#

这是我的代码:

class sample
    {
        public string str1 = "";
        public string str2 = "";
        public sample()
        {
            sample smp = new sample("BB", "EE");
        }
        public sample(string s1, string s2)
        {
            this.str1 = s1;
            this.str2 = s2;
        }
        public static void Main()
        {
            sample smpl = new sample();
            Console.WriteLine(smpl.str1);
            Console.WriteLine(smpl.str2);
            Console.ReadLine();

        }
    }
Run Code Online (Sandbox Code Playgroud)

我给我的变量赋予了两个字符串值,但没有发生任何事情.请问你能告诉我哪个问题?

Ali*_*tad 19

您想用来this("BB", "EE")调用其他构造函数.您在无参数构造函数中所做的是创建一个分配给局部变量的独立临时实例smp,该实例对正在构造的对象str1或str2成员没有影响.

class sample
{
    public string str1 = "";
    public string str2 = "";
    public sample() : this("BB", "EE")
    {

    }
    public sample(string s1, string s2)
    {
        this.str1 = s1;
        this.str2 = s2;
    }
    public static void Main()
    {
        sample smpl = new sample();
        Console.WriteLine(smpl.str1);
        Console.WriteLine(smpl.str2);
        Console.ReadLine();

    }
}
Run Code Online (Sandbox Code Playgroud)


Pla*_*ure 10

您sample在无参数构造函数中本地声明了一个对象.这与this您实际构建的对象是分开的.当该构造函数返回时,smp不再在范围内并且将被垃圾收集,同时您还没有初始化您的字符串(如您所注意到的).

您有两种选择:

  1. 只需将字符串初始化为其默认值(请注意,如果您希望在所有构造函数中出现通用逻辑,则另一个选项可能更好)

    public sample()
    {
        this.str1 = "BB";
        this.str2 = "EE";
    }
    public sample(string s1, string s2)
    {
        this.str1 = s1;
        this.str2 = s2;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用this构造函数声明中的关键字来引用其他构造函数

    public sample() : this("BB", "EE")
    {
        // no need to do anything else, but you can do other things if the situation warrants
    }
    public sample(string s1, string s2)
    {
        this.str1 = s1;
        this.str2 = s2;
    }
    
    Run Code Online (Sandbox Code Playgroud)


Cod*_*ter 5

您正在创建无sample参数构造的新实例.这会在返回后立即丢弃,并且不会影响sample您正在使用的当前实例.

您可能希望将其更改为:

public sample()
{
    this.str1 = "BB";
    this.str2 = "EE";    
}
Run Code Online (Sandbox Code Playgroud)

哪里this.可以省略.

正如其他人指出的那样,另一种选择是使用以下方法调用其他构造函数:

public sample() 
    : this("BB", "EE")
{

}
Run Code Online (Sandbox Code Playgroud)

读一下这里.