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

问题描述

关于如何使用反射和 LINQ 以类型安全的方式引发 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":
            ...

        ....
    }
}

有没有办法避免在 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 表达式转换为反射 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)
    {
        // ...
    }
}

很遗憾,您不能使用 switch 语句,因为属性名称不再是编译时常量.

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

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

06-21 08:05