9

The new C# 6.0 nameof is great in the PropertyChanged pattern for propagating property changes using something like:

private string _myProperty;

public string MyProperty
{
    get
    {
        return _myProperty;
    }
    set
    {
        _myProperty= value;
        OnPropertyChanged(nameof(MyProperty));
    }
}

When listening of property changes I use this (yes, even with ugly hardcoded strings):

    private void OnMyObjectPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        switch (args.PropertyName)
        {
            case "MyProperty":
                DoSomething();
                break;
        }
    }

With the new nameof expressions would this code compile / work?

private void OnMyObjectPropertyChanged(object sender, PropertyChangedEventArgs args)
{
    switch (args.PropertyName)
    {
        case nameof(MyObject.MyProperty):
            DoSomething();
            break;
    }
}
4

1 回答 1

15

根据这个问题nameof关键字的评估是在编译时完成的。这将使它成为一个常量,它将在switch语句中起作用。

当您查看此代码的编译输出时可以证明这一点:

using System;

public class Program
{
    public string A { get; set; }

    public static void Main()
    {
        string a = "A";

        switch (a)
        {
            case nameof(Program.A):
            {
                Console.WriteLine("Yes!");
                break;
            }
        }

    }
}

输出:

是的!

于 2015-05-07T10:02:27.887 回答