簡體   English   中英

將未初始化的參數傳遞給方法時的ref關鍵字

[英]ref keyword when passing uninitialized parameter to a method

WinRT項目中的BindableBase抽象基類定義如下:

[Windows.Foundation.Metadata.WebHostHidden]
public abstract class BindableBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
    {
        if (object.Equals(storage, value)) return false;

        storage = value;
        this.OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var eventHandler = this.PropertyChanged;
        if (eventHandler != null)
        {
            eventHandler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

沒關系。

現在我看到許多文章試圖實現這個類,做這樣的事情:

private  int _timeEstimate;
        public int TimeEstimate
        {
            get { return this._timeEstimate; }
            set { this.SetProperty(ref this._timeEstimate, value); }
        }

_timeEstimate沒有初始化,如何使用ref傳遞? 有什么我想念的嗎? 這真讓我感到沮喪,我錯過了什么,我甚至在微軟的考試准備書中找到了同樣的寫作!

_timeEstimate是一個字段。 在構造class期間(在構造函數觸發之前),字段顯式初始化為零值。 對於struct ,它們必須在構造函數中顯式初始化,或者如果使用默認構造函數初始化類型則為零(旁注:技術上struct沒有默認構造函數,但C#和IL不同意這一點,所以我們為方便起見,只需將new SomeStruct()稱為構造函數; p)

基本上:它已初始化。

它是未初始化的局部變量

暫無
暫無

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

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