簡體   English   中英

我可以聲明全局變量並在不引用其類的情況下從任何地方引用它嗎?

[英]Can I declare a global variable and refer to it from anywhere without referring to its class?

我有一個C#控制台應用程序。 例如,我希望主程序確定我是否處於調試模式,並設置一個變量,例如... g_Bypass,每個類都可以引用該變量。

例:

class test
{
    public static bool g_testMode;

    test()
    {
        g_testMode = true;  // read from the database.
        // more code...
        Object1 _obj = new Object1();
        // do more stuff with _obj...
    }
}

class Object1
{

    public Object1()
    {
        // constructor
        if (g_testMode)          // << I'd like to just refer to it this way!
        {
            // do something
        }
    }
}

在.Net中,每個變量和方法都必須包含在一個類中。 但是,可以在全局范圍內訪問靜態公共成員,但是在類之外使用靜態公共成員時,必須使用類名作為前綴。 但是你可以打電話給你的類g ,比代替g_testMode你寫g.testMode 盡管不鼓勵使用小寫的類名,但最好使用G.testMode

您的示例將讀取為:

static class G //static is not necessary here
{
    public static bool testMode;
}
class test
{
    test()
    {
        G.testMode = true;  // read from the database.
        // more code...
        Object1 _obj = new Object1();
        // do more stuff with _obj...
    }
}

class Object1
{

    public Object1()
    {
        // constructor
        if (G.testMode)          // << I'd like to just refer to it this way!
        {
            // do something
        }
    }
}

如果是調試模式,則擔心您可以通過執行以下操作在方法或類定義中的成員變量中創建局部變量:

#if DEBUG
    bool debug = true;
#else
    bool debug = false;
#endif

如果出於某種原因要創建全局靜態:

public static class Test {
#if DEBUG
    public static bool debug = true;
#else
    public static bool debug = false;
#endif
}

這需要在對象外部作為Test.debug進行引用

您需要在項目的構建屏幕中定義變量DEBUG

只是因為您可以做到這一點,所以您不應該!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM