簡體   English   中英

有沒有一種快速的方法可以將 C# 中的結構歸零?

[英]Is there a quick way of zeroing a struct in C#?

這一定已經回答了,但我找不到答案:

是否有一種快速且提供的方法可以將 C# 中的struct歸零,或者我必須自己提供someMagicalMethod嗎?

需要明確的是,我知道該結構將被初始化為 0,我想知道是否有一種將值重置為 0 的快速方法。

IE,

struct ChocolateBar {
    int length;
    int girth;
}

static void Main(string[] args) {
    ChocolateBar myLunch = new ChocolateBar();
    myLunch.length = 100;
    myLunch.girth  = 10;

    // Eating frenzy...
    // ChocolateBar.someMagicalMethod(myLunch);

    // myLunch.length = 0U;
    // myLunch.girth = 0U;
}

只需使用:

myLunch = new ChocolateBar();

myLunch = default(ChocolateBar);

myLunch = default;

這些等效於1 ,並且最終都會為myLunch分配一個新的“所有字段設置為零”值。

此外,理想情況下不要使用可變結構開始 - 我通常更喜歡創建一個不可變的結構,但它具有返回具有不同設置的特定字段的值的方法,例如

ChocolateBar myLunch = new ChocolateBar().WithLength(100).WithGirth(10);

...當然也提供適當的構造函數:

ChocolateBar myLunch = new ChocolarBar(100, 10);

1至少對於在 C# 中聲明的結構。 值類型可以在 IL 中具有自定義的無參數構造函數,但相對難以預測 C# 編譯器將調用它的情況,而不是僅使用默認的“零”值。

只需在代碼中調用無參數構造函數:

ChocolateBar chocolateBar = new ChocolateBar();

一個新的ChocolateBar被初始化為零。 所以:

myLunch = new ChocolateBar();

這只有效,因為ChocolateBar是結構/值類型。 如果ChocolateBar是一個類,這將創建一個新的ChocolateBar並將myLunch更改為指向它。 存儲在myLunch中的ChocolateBar的值將為零。 舊的 ChocolateBar 將保持不變,並最終被垃圾收集器聲明,除非其他引用也指向舊的 myLunch。

struct是一種value type 默認情況下,它們在初始化時設置為零。

int默認值為零。 您無需將其設置為零。

只需將Zero添加到您的結構中,如下所示。 此外,作為一個側面,考慮在您的結構中使用構造函數,以便您可以參數化您的變量而不是單獨設置它們:

public struct ChocolateBar {
    int length;
    int girth;

    public static ChocolateBar Zero { get; }

    public ChocolateBar(int length, int girth) {
        this.length = length;
        this.girth = girth;
    }
}

class OtherClass() {
    ChocolateBar cB = new ChocolateBar(5, 7);
    cB = ChocolateBar.Zero();

    Console.Writeline( (cB.length).ToString() ); // Should display 0, not 5
    Console.Writeline( (cB.girth).ToString() ); // Should display 0, not 7
}

Zero獲得 0 值的原因是因為int lengthint girth的默認(靜態)值是 0,正如上面其他人提到的。 Zero本身是靜態的,因此您可以直接訪問它而無需對象引用。

換句話說,大多數(如果不是全部)你的結構應該有一個Zero屬性,以及一個constructor 它超級好用。

您可以通過這種方式修改您的結構:

struct ChocolateBar {
    int length;
    int girth;
    public void Clear()
    {
        this = new ChocolateBar();
    }
}

並輕松地在您的代碼中使用它:

ChocolateBar cb = new ChocolateBar();
//some stuff here
cb.Clear();

暫無
暫無

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

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