[英]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. 我想访问在同一页面中创建的新类中在Main class中声明为public的变量。 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. 在这种情况下,应使用构造函数注入,并将is_arrived的值传递给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. 这种方法的一个问题是,如果在父类中更改了is_arrived值,它将失去同步。 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. 但是,不应鼓励这种做法,并应采用更好的设计方法来消除这种做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.