简体   繁体   中英

How to access a variable declared in a page to a inner class?

I want to access a variable which is declared as public in Main class to a new class created within the same page. I have done like below. But cant access the variable in that class

public sealed partial class MainPage : Page
{ 
    public bool is_arrived = false;
    public MainPage()
    {
        this.InitializeComponent();
        bool is_arrived=true;
        CallingWebServices asyn_task = new CallingWebServices();
    }
    public class CallingWebServices
    {
        //want to access variable "is_arrived" here.
    }
}

In such cases you should use constructor injection and pass the value of is_arrived to CallingWebServices.

public sealed partial class MainPage : Page
{ 
    public bool is_arrived = false;
    public MainPage()
    {
        this.InitializeComponent();
        bool is_arrived=true;
        CallingWebServices asyn_task = new CallingWebServices(is_arrived);
    }
    public class CallingWebServices
    {
         private bool _isArrived;
         public CallingWebServices(bool isArrived)
         {
            _isArrived=isArrived;
         }
        //want to access variable "is_arrived" here.
    }
}

One problem with this approach is that is_arrived value will loose sync if you change it in the parent class. So other approach is to pass the reference of the parent class to the inner class.

public sealed partial class MainPage : Page
{ 
    public bool is_arrived = false;
    public MainPage()
    {
        this.InitializeComponent();
        bool is_arrived=true;
        CallingWebServices asyn_task = new CallingWebServices(this);
    }
    public class CallingWebServices
    {
         private MainPage _Instance;
         public CallingWebServices(MainPage instance)
         {
            _Instance=instance;
         }
        //Access variable "instance.is_arrived" here.
     }
}

However such practices should be discouraged and should be eliminated by having a better design approach.

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