2013-12-12 27 views
0

我将如何使变量cRentStart在上述类中可供我的程序中的所有类访问?使变量可以访问我的课程的所有区域

目前我在Form1使用dateCheck初始化时,所以我想保持这一点,并继续在其他情况下使用它叫私人无效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"); 
    } 
} 
+1

将它声明为Form1的“内部”或“公共”属性?编辑:虽然,我不确定你在问题标题中的问题:“所有私人课程都可以访问” –

+0

@ChrisSinclair在我的代码中,这看起来如何? – theshizy

+1

我猜你需要一个关于基本C#面向对象编程的入门书;基本上基本的类结构,字段,属性等。快速谷歌从MSDN产生这个介绍,快速浏览似乎是一个半体面的来源,绝对是更多在线可用吨:http://msdn.microsoft.com/en-us/beginner/bb308750.aspx –

回答

1

你想要的是一个全局变量。
关于全局变量请参阅this page

一些注意事项:

  • 公共全局变量是在以往任何时候该对象被解析访问。
  • 公开的静态全局变量将被访问,无论你有没有暴露类。
  • 私有全局变量的工作方式与期望它们只能在该类/对象的内部使用相同。

namespace MyApp 
{ 
    public class MyClass 
    { 
     public static string MyString { get; set; } 

     public MyClass() 
     { 

     } 
    } 

    public class MyOtherClass 
    { 
     public MyOtherClass() 
     { 
      MyClass.MyString = "Test"; 
     } 
    } 
} 
+0

因此,在换句话说 - http://pastebin.com/00z4PA8M – theshizy

+0

见增加的例子 –

相关问题