2009-01-13 45 views
1

全局设置以这篇文章的类和结构为例:获得在C#

http://msdn.microsoft.com/en-us/library/ms173109.aspx

namespace ProgrammingGuide 
{ 
    // Class definition. 
    public class MyCustomClass 
    { 
     // Class members: 
     // Property. 
     public int Number { get; set; } 

     // Method. 
     public int Multiply(int num) 
     { 
      return num * Number; 
     } 

     // Instance Constructor. 
     public MyCustomClass() 
     { 
      Number = 0; 
     } 
    } 
    // Another class definition. This one contains 
    // the Main method, the entry point for the program. 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // Create an object of type MyCustomClass. 
      MyCustomClass myClass = new MyCustomClass(); 

      // Set the value of a public property. 
      myClass.Number = 27; 

      // Call a public method. 
      int result = myClass.Multiply(4); 
     } 
    } 
} 

假设我想利用在主程序 定义的“MyClass的”的该计划的其他部分仿佛是全球课程。

我该怎么做?现在

回答

2
static MyCustomClass myClass; 
public static MyCustomClass MyClass {get {return myClass;}} 
static void Main(string[] args) 
{ 
    // Create an object of type MyCustomClass. 
    myClass = new MyCustomClass(); 

    ... 
} 

可以使用Program.MyClass

+0

另外,看看单身模式:www.pobox.com/~skeet/csharp/singleton.html – 2009-01-13 23:14:47

0

类似下面的例子。

class Program 
{ 
    public MyCustomClass myClass; 

    public Program() 
    { 
     // Create an object of type MyCustomClass. 
     myClass = new MyCustomClass(); 

     // Set the value of a public property. 
     myClass.Number = 27; 

     // Call a public method. 
     int result = myClass.Multiply(4); 
    } 

    static void Main(string[] args) 
    { 
     Program program = new Program(); 
    } 
}