2016-08-21 52 views
0

我有這行代碼:C# - 從另一個.CS訪問ToolStripMenuItem控制文件

checkForUpdatesToolStripMenuItem.Enabled = true; 

但是,它給我的錯誤:

The name 'checkForUpdatesToolStripMenuItem' does not exist in the current context

的問題是,怎麼辦我從我工作的當前.CS文件訪問項目(checkForUpdatesToolStripMenuItem),其中'checkForUpdatesToolStripMenuItem'是表單的一部分?

感謝。相同的命名空間下

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Send_ToolStrip_Data_To_Instance_Class() 
    { 
     My_Other_CS_File other_File = new My_Other_CS_File(); 
     other_File.Act_On_ToolStrip_Item(checkForUpdatesToolStripMenuItem.Enabled); 
    } 
} 
public class My_Other_CS_File 
{ 
    public void Act_On_ToolStrip_Item(bool enabled) 
    { 
     //do something 
    } 
} 

回答

0

您可以將值傳遞給其他類。我們使用不同的文件以方便。 public partial class Form1:Form { //這是項目中主窗體的窗體類。這是程序啓動時線程的位置。將不存在其它實例類創建它們

public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void hello() 
    { 
     //I can only call hello from inside this class. 
     My_Other_CS_File other_File = new My_Other_CS_File(); 
     //you created this instance class here. It will only exist until "hello" finishes running, then it will disappear. 
     string hello = "hi"; 
     //the only way to get the string hello to the class you created is to pass it. 
     other_File.SayHello(hello); 
     //other_file is done. It will disappear now if you want it again you will have to create a new instance 
    } 
} 
public class My_Other_CS_File 
{ 
    public void SayHello(string hi) 
    { 
     //here, the string Hi is passed from the form class 
     Console.WriteLine(hi); 
     //even though this class was created by the form class, it has access to any public static classes. 
     Console.WriteLine(Global.helloString); 
    } 
} 
public static class Global 
{ 
    //anything marked "public static" here will be visible to any class under the same namespace. This class is niether created nor destroyed - it always exists. hat's the difference bewtween static and instance. 
    public static string helloString = "howdy"; 
} 

}

+0

我不明白你如何使用這些類到。我是一個老派的C程序員,所以理解這很奇怪。我在哪裏放這些類?在我的Form.CS代碼(最高級別/主)或CS文件中,我正在嘗試使「checkForUpdatesToolStripMenuItem」工作? – t0rxe

+0

類可以在一個文件中或在單獨的文件中。想象一下實例類,比如獨立對象,它們只能與其創建者通信。如果您從表單類內部創建實例類(cs文件),則需要從表單類傳遞任何內容到它。或者,您可以創建對所有實例類都可見的靜態類(使用public static class myClass {}實際代碼是在一個文件中還是在另一個文件中是無關緊要的。 –

+0

命名空間包含所有內容,不管它是在一個文件中還是在一個文件中很多,就C#而言,只要代碼位於同一個命名空間下,代碼的位置就不重要了。實例類(用新的ClassName()創建的類)只有它們的創建者才知道。基本上, –

0
namespace SO_Question_win 

{// EVERYTHIG很可能會成爲在銷售文件中儘可能C#關注:

+0

簡而言之,類就像舊式函數。如果您需要重複性代碼或需要組織一個「功能」,只需將它放在課程中,您可以隨時調用它。然而,與2D「函數」不同,類可以有許多不同的變量,方法 - 它們可以像迷你程序一樣,可以繼承和完成各種各樣的很酷的事情。但基本上,它們就像超功能。 –

相關問題