2013-12-12 28 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

見增加的例子 –

相關問題