我看了这篇介绍如何在POCO属性之间进行数据绑定的帖子:Data Binding POCO Properties。Bevan在评论中提供了一个简单的Binder类,用于实现此类数据绑定。它对我所需的功能非常有效,但我想实现Bevan提出的一些改进建议,包括:
- 检查源和目标是否已分配
- 检查源属性名和目标属性名是否存在
- 检查两个属性之间的类型兼容性
此外,考虑到通过字符串指定属性容易出错,可以使用Linq表达式和扩展方法来替代。然后,您可以写成:
Binder.Bind( source, "Name", target, "Name")
你可以编写代码
source.Bind( Name => target.Name);
我相信我可以处理前三个问题(尽管您可以包括这些更改),但我不知道如何使用Linq表达式和扩展方法来编写代码,而不使用属性名字符串。
有什么技巧吗?
以下是在链接中找到的原始代码:
public static class Binder
{
public static void Bind(
INotifyPropertyChanged source,
string sourcePropertyName,
INotifyPropertyChanged target,
string targetPropertyName)
{
var sourceProperty
= source.GetType().GetProperty(sourcePropertyName);
var targetProperty
= target.GetType().GetProperty(targetPropertyName);
source.PropertyChanged +=
(s, a) =>
{
var sourceValue = sourceProperty.GetValue(source, null);
var targetValue = targetProperty.GetValue(target, null);
if (!Object.Equals(sourceValue, targetValue))
{
targetProperty.SetValue(target, sourceValue, null);
}
};
target.PropertyChanged +=
(s, a) =>
{
var sourceValue = sourceProperty.GetValue(source, null);
var targetValue = targetProperty.GetValue(target, null);
if (!Object.Equals(sourceValue, targetValue))
{
sourceProperty.SetValue(source, targetValue, null);
}
};
}
}