簡體   English   中英

對於靜態成員,C#中是否存在“this”的等價物?

[英]Is there an equivalent of 'this' in C# for static members?

是否有一個相當於this在C#中的靜態成員?

我喜歡用this來使我的代碼更具可讀性,但是想知道是否有靜態成員的等價物。

我想如果你使用this. 為了強調你指的是實例成員,靜態成員中的等價物將是使用ClassName.

但在風格上,為什么添加不會改變含義的代碼?


編輯以添加各種說明:

我的上一句話可以用這些例子來說明:

class Example1
{
    public int J { get; set; }

    public Example1()
    {
        J = 0;
    }

    // These two methods have *exactly* the same CIL
    public int InstanceMethodLong()
    {
        return this.J;
    }

    public int InstanceMethodShort()
    {
        return J;
    }
}

this. InstanceMethodLong因為相比沒有改變的意思InstanceMethodShort

靜態:

class Example2
{
    public static int K { get; set; }

    static Example2()
    {
        K = 0;
    }

    // These two methods have *exactly* the same CIL
    public int StaticMethodLong()
    {
        return Example2.K;
    }

    public int StaticMethodShort()
    {
        return K;
    }

Example2. StaticMethodLong因為相比沒有改變的意思StaticMethodShort

在這兩種情況下,添加限定符會產生相同的CIL,相同的行為,並且是寫入,讀取和理解的更多源。 風格上 - 我很高興地接受這是一個代碼風格的問題 - 我認為沒有理由在那里。


使用下划線前綴,情況略有不同:

class Example3
{
    int _j;

    public int J
    {
        get { return _j; }
        set
        {
            _j = value;
            // and do something else,
            // to justify not using an auto-property 
        }
    }

    public Example3()
    {
        J = 0;
    }

    public int MethodWithParameter(int j)
    {
        // Now there is a *difference* between
        return j;

        // and
        return _j;
    }
}

在這里,在MethodWithParameter ,引用_jj之間存在差異 ,因此我們故意並明確地表達不同的含義。 確實,編譯器並不關心我們所謂的變量名稱,但它確實關心我們所指的變量! 所以在身體MethodWithParameter ,使用或不使用下划線只是風格上,它的語義。 這不是我們在這個問題中解決的特殊問題。

由於靜態成員不屬於任何特定實例(因為this指的是對象的實例,每個實例可能有不同的設置),所以您想要做的是使用ClassName.Member而不是this.Member

public class Orange
{
    public static string Tastes = "sweet";

    public static string FoodType(){
        return "fruit";
    }
}

將被稱為:

Console.WriteLine(Orange.Tastes);

靜態方法也是如此:

Console.WriteLine(Orange.FoodType()).

請注意,這是一個僅供演示的人為舉例。 :)

您可以使用類名來引用其他靜態屬性。

你的代碼變得更容易復制/粘貼,但這並不總是壞事。

不幸的是,靜態方法沒有this 為了幫助區分靜態成員和類成員,我在其前面添加了類名。

class Test {
  static Regex TextRegex = new Regex(...);

  public static bool TestString(string input) {
    return Test.TextRegex.IsMatch(input);
  }
}

我喜歡“這個”,也可以從狀態正在發生變化的第一眼看出來。 在這種情況下,您可能需要考慮靜態成員的類型名稱。

暫無
暫無

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

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