简体   繁体   中英

Getting values from a multiple constructor

Here is the sample code:

class Class1
{
    string a;

    public Class1(string over) : base()
    {
       this.a = over;
       Console.WriteLine(a);
    }

    public Class1(bool check)
    {
       if(check)
         Console.WriteLine(a);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Class1 myClass1 = new Class1("test");
        Class1 myClass2 = new Class1(true);
        Console.ReadLine();
    }
}

What I want to happen is to get the value of string a from the 1nd Constructor Class1(string) and display it to Constructor Class1(bool) . How can I do that?

You have two different instances of Class1: myClass1 and MyClass2 If 'a' needs to be shared across instances, then you can make it static.

That way, setting 'a' in any instance of Class1 will apply to all instances.

Make string a static. That way, all instances of Class1 reference the same string.

This should work, but i dont think you should be doing that.

class Class1 {     

    static string a;  

    public Class1(string over) : base() {        
        a = over;        
        Console.WriteLine(a);     
    }      
    public Class1(bool check)     {        
        if(check)          
            Console.WriteLine(a);     
        } 
    }  

    class Program {     
        static void Main(string[] args)     {         
            Class1 myClass1 = new Class1("test");         
            Class1 myClass2 = new Class1(true);         
            Console.ReadLine();     
        } 
    } 
}

Pass myClass1 to myClass2 in a method call (or in the constructor)

It is hard to tell what to do because Class1, a, over, check. They don't make sense to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM