Visual C# - Access instance of object created in one class in another

前端 未结 4 793
Happy的楠姐
Happy的楠姐 2020-12-08 16:54

I apologize in advance with what will probably be a fairly easy/quick answer based on scope, but I\'ve looked everywhere and am surprised to not come up with an answer.

4条回答
  •  独厮守ぢ
    2020-12-08 17:39

    You'll need to declare the Soldier instance in in a higher scope.

    One way of doing this would be to declare it inside Form1, then pass it to Form2, and so on.

    public class Form1
    {
        private Soldier tempSoldier = new Soldier();
    
        private void button1_Click(object sender, EventArgs e)
        {
            tempSoldier = new Soldier();
            tempSoldier.surname = textbox1.text;
        }
    
        private void GotoNextStep()
        {
            // pass the existing instance to the next form
            Form2 form2 = new Form2(tempSoldier);
    
            // display form 2 ...
        }
    }
    

    Another possibility is to use a singleton variable in a class that all the forms have access to.

    public class MyAppManager
    {
        private static readonly Soldier _soldier = new Solider();
    
        public static Soldier SoldierInstance
        {
            get { return _soldier; }
        }
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        MyAppManager.SoldierInstnace.surname = textbox1.text;
    }
    

    The former approach is ok if there's a distinct sequence to the forms; the latter is better if difference forms could be used at different times or revisited.

提交回复
热议问题