我正在看这篇文章,它描述了一种在 POCO 属性之间进行数据绑定的简单方法:数据绑定 POCO 属性
Bevan 的评论之一包括一个简单的 Binder 类,可用于完成此类数据绑定。它非常适合我的需要,但我想实施 Bevan 为改进课程而提出的一些建议,即:
- 检查是否分配了源和目标
- 检查 sourcePropertyName 和 targetPropertyName 标识的属性是否存在
- 检查两个属性之间的类型兼容性
此外,鉴于按字符串指定属性容易出错,您可以改用 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);
}
};
}
}