在C#中获取全局设置

时间:2009-01-13 23:08:40

标签: c# global-variables

以类和结构为例:

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);
        }
    }
}

假设我想使用Main例程中定义的“myClass” 在该计划的其他地方,好像它是一个全球级的。

我该怎么做?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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();
    }
}