Switch-Case on Class.PropertyName (not value)

前端 未结 2 483
面向向阳花
面向向阳花 2021-02-06 10:31

I have a class which implements INotifyPropertyChanged like this:

public class Person : INotifyPropertyChanged {

    public event PropertyChangedEv         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 10:47

    In C# 6.0, you can use the nameof() keyword.

    The keyword is replaced by string literals at compile time. So it's much better than using lambda expression with code that digs the name of your symbol at runtime on a performance point of view, and it also works with switch() statements:

    switch(e.PropertyName)
    {
        case nameof(Foo.Bar):
            break;
    }
    

    You will also get a compile time error if you change the name of the property in the class, but forget to change it in your switch statement. So this approach is much less bugprone.

提交回复
热议问题