我想访问一个在Main class中声明为public的变量,以访问在同一页面中创建的新类。我已经做了如下。但是无法访问该类中的变量
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.
}
}
答案 0 :(得分:0)
在这种情况下,应使用构造函数注入,并将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.
}
}
此方法的一个问题是,如果在父类中更改is_arrived值,则会失去同步。因此,另一种方法是将父类的引用传递给内部类。
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.
}
}
但是,应避免这种做法,并应通过采用更好的设计方法来消除这种做法。