Switch-Case on Class.PropertyName (not value)

前端 未结 2 521
面向向阳花
面向向阳花 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:33

    You can use Expression> to do what you want.

    Define this method:

    private string ToPropertyName(Expression> @this)
    {
        var @return = string.Empty;
        if (@this != null)
        {
            var memberExpression = @this.Body as MemberExpression;
            if (memberExpression != null)
            {
                @return = memberExpression.Member.Name;
            }
        }
        return @return;
    }
    

    Then you can write this:

    void Person_PropertyChanged(object sender, PropertyChangedEventArgs e){
        switch (e.PropertyName)
        {
            case ToPropertyName(() => Person.Color);
                //some stuff
                break;
            default:
                break;
        }
    }
    

    Now you have some strongly-typed joy. :-)


    To get switch-like functionality without switch and messy if/then/else you can do this:

    void Person_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        var @switch = new Dictionary()
        {
            { ToPropertyName(() => Person.Color), () => { /* some stuff */ } },
            { ToPropertyName(() => Person.Size), () => { /* some other stuff */ } },
            { ToPropertyName(() => Person.Shape), () => { /* some more stuff */ } },
        };
    
        if (@switch.ContainsKey(e.PropertyName))
        {
            @switch[e.PropertyName]();
        }
        else
        {
            /* default stuff */
        }
    }
    

提交回复
热议问题