为什么 INotifyPropertyChanged 的​​ SetProperty() 方法需要一个 ref 参数?

Mar*_*arc 1 c# ref inotifypropertychanged

考虑到 INotifyPropertyChanged 的​​实现通常如下所示:

    public class Observable : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void SetProperty<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
        {
            if (Equals(storage, value))
            {
                return;
            }

            storage = value;
            OnPropertyChanged(propertyName);
        }

        protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
Run Code Online (Sandbox Code Playgroud)

为什么该SetProperty方法需要 ref 参数?几乎不可能将类字段以外的任何内容传递给该方法,因此无论如何它应该始终是引用类型?

注意:我问这个问题是因为我想将此方法用于通过foreach循环枚举的项目,该方法不适用于ref关键字。

Jon*_*eet 5

目的是通过引用传递字段以及新值。

如果这不是ref参数,您将传递该字段的...此时此语句:

storage = value;
Run Code Online (Sandbox Code Playgroud)

......将毫无意义。这会改变parameter的值,但根本不会修改该字段

这是一个完整的示例来演示差异:

using System;

class Program
{
    static string field;

    static void Main()
    {
        field = "initial value";
        Console.WriteLine($"Before Modify1: {field}");

        Modify1(field, "new value for Modify1");
        Console.WriteLine($"After Modify1: {field}");

        Modify2(ref field, "new value for Modify2");
        Console.WriteLine($"After Modify2: {field}");
    }

    static void Modify1(string storage, string value)
    {
        // This only changes the parameter
        storage = value; 
    }

    static void Modify2(ref string storage, string value)
    {
        // This changes the variable that's been passed by reference,
        // e.g. a field
        storage = value;
    }        
}
Run Code Online (Sandbox Code Playgroud)

输出:

Before Modify1: initial value
After Modify1: initial value
After Modify2: new value for Modify2
Run Code Online (Sandbox Code Playgroud)

如您所见,Modify1(without ref) 根本没有修改该字段,而Modify2确实如此。