将未初始化的参数传递给方法时的ref关键字

时间:2014-02-17 13:28:01

标签: c# mvvm windows-runtime ref

BindableBase项目中的WinRT抽象基类定义如下:

[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传递?有什么我想念的吗?这真让我感到沮丧,我想念的是什么,我甚至在微软的考试准备书中找到了相同的写作!

1 个答案:

答案 0 :(得分:6)

_timeEstimate是一个字段。在构造class期间(在构造函数触发之前),字段显式初始化为零值。对于struct,它们必须在构造函数中显式初始化,或者如果使用默认构造函数初始化类型则为零(旁注:技术上struct没有默认构造函数,但是C#和IL对此不一致,所以为方便起见,我们只需将new SomeStruct()称为构造函数; p)

基本上:它已初始化。

局部变量未初始化。