处理PropertyChanged以类型安全的方式 [英] Handling PropertyChanged in a type-safe way
问题描述
有很多关于如何使用反射和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表达式转换成Reflection < c $ c> PropertyInfo object(从我这里的答案):
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屋!