[英]Making variable accessible to all areas of my class
如何使上述类中的变量cRentStart可供程序中的所有类访问?
目前,我在form1初始化时使用dateCheck ,因此我想保留它,并继续在另一个名为private void viewOverdue_Click的事件中使用它
public Form1()
{
InitializeComponent();
viewRent.ForeColor = Color.Red;
dateCheck();
}
void dateCheck()
{
CurrentDate.Text = "" + DateTime.Now;
DateTime cRentStart, cRentEnd;
DateTime today = DateTime.Now;
if (today.DayOfWeek == DayOfWeek.Monday)
{
cRentStart = today.AddDays(-5);
cRentEnd = today.AddDays(2);
CurrentRent.Text = "Current Rent Week: " + cRentStart.ToString("dd/MM/yyyy") + " - " + cRentEnd.ToString("dd/MM/yyyy");
}
else if (today.DayOfWeek == DayOfWeek.Tuesday)
{
cRentStart = today.AddDays(-6);
cRentEnd = today.AddDays(1);
CurrentRent.Text = "Current Rent Week: " + cRentStart.ToString("dd/MM/yyyy") + " - " + cRentEnd.ToString("dd/MM/yyyy");
}
else if (today.DayOfWeek == DayOfWeek.Wednesday)
{
cRentStart = today.AddDays(0);
cRentEnd = today.AddDays(7);
CurrentRent.Text = "Current Rent Week: " + cRentStart.ToString("dd/MM/yyyy") + " - " + cRentEnd.ToString("dd/MM/yyyy");
}
else if (today.DayOfWeek == DayOfWeek.Thursday)
{
cRentStart = today.AddDays(-1);
cRentEnd = today.AddDays(6);
CurrentRent.Text = "Current Rent Week: " + cRentStart.ToString("dd/MM/yyyy") + " - " + cRentEnd.ToString("dd/MM/yyyy");
}
else if (today.DayOfWeek == DayOfWeek.Friday)
{
cRentStart = today.AddDays(-2);
cRentEnd = today.AddDays(5);
CurrentRent.Text = "Current Rent Week: " + cRentStart.ToString("dd/MM/yyyy") + " - " + cRentEnd.ToString("dd/MM/yyyy");
}
else if (today.DayOfWeek == DayOfWeek.Saturday)
{
cRentStart = today.AddDays(-3);
cRentEnd = today.AddDays(4);
CurrentRent.Text = "Current Rent Week: " + cRentStart.ToString("dd/MM/yyyy") + " - " + cRentEnd.ToString("dd/MM/yyyy");
}
else if (today.DayOfWeek == DayOfWeek.Sunday)
{
cRentStart = today.AddDays(-4);
cRentEnd = today.AddDays(3);
CurrentRent.Text = "Current Rent Week: " + cRentStart.ToString("dd/MM/yyyy") + " - " + cRentEnd.ToString("dd/MM/yyyy");
}
}
您想要的称为全局变量。
请参见本页上的全局变量。
一些注意事项:
例
namespace MyApp
{
public class MyClass
{
public static string MyString { get; set; }
public MyClass()
{
}
}
public class MyOtherClass
{
public MyOtherClass()
{
MyClass.MyString = "Test";
}
}
}
通过赋予它正确的范围... http://msdn.microsoft.com/zh-cn/library/ms973875.aspx
目前,cRentStart的范围仅限于dateCheck方法。 在具有适当访问器的范围之外声明它,以从其他位置访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.