在类型安全的方式处理的PropertyChanged [英] Handling PropertyChanged in a type-safe way

查看:122
本文介绍了在类型安全的方式处理的PropertyChanged的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有过许多有关如何使用反射和LINQ to提高类型安全方式的PropertyChanged事件,而使用字符串的文章。

There have been plenty of articles about how to use reflection and LINQ to raise PropertyChanged events in a type-safe way, without using strings.

但没有任何办法的消耗的PropertyChanged的一个类型安全的方式活动?目前,我在做这个

But is there any way to consume PropertyChanged events in a type-safe manner? Currently, I'm doing this

void model_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    switch (e.PropertyName)
    {
        case "Property1":
            ...
        case "Property2":
            ...

        ....               
    }
}

有什么办法避免硬-coding字符串switch语句来处理不同的属性?一些类似LINQ-或基于反射的方法?

Is there any way to avoid hard-coding strings in a switch statement to handle the different properties? Some similar LINQ- or reflection-based approach?

推荐答案

让的声明,可以把lambda表达式到一个反射<$的方法C $ C>的PropertyInfo 对象(的从我的回答这里服用):

Let’s declare a method that can turn a lambda expression into a Reflection PropertyInfo object (taken from my answer here):

public static PropertyInfo GetProperty<T>(Expression<Func<T>> expr)
{
    var member = expr.Body as MemberExpression;
    if (member == null)
        throw new InvalidOperationException("Expression is not a member access expression.");
    var property = member.Member as PropertyInfo;
    if (property == null)
        throw new InvalidOperationException("Member in expression is not a property.");
    return property;
}

和再拿它来获取属性的名称:

And then let’s use it to get the names of the properties:

void model_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == GetProperty(() => Property1).Name)
    {
        // ...
    }
    else if (e.PropertyName == GetProperty(() => Property2).Name)
    {
        // ...
    }
}

可惜你不能使用开关语句,因为属性名称不再是编译时间常数。

Unfortunately you can’t use a switch statement because the property names are no longer compile-time constants.

这篇关于在类型安全的方式处理的PropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆