我正在看这篇文章,它描述了在POCO属性之间进行数据绑定的简单方法:数据绑定POCO属性
Bevan的评论之一包括一个简单的Binder类,可用于完成此类数据绑定.它对我需要的东西很有用,但我想实现Bevan为改进课程所做的一些建议,即:
此外,鉴于按字符串指定属性容易出错,您可以使用Linq表达式和扩展方法.然后而不是写作
Binder.Bind( source, "Name", target, "Name")
Run Code Online (Sandbox Code Playgroud)
你可以写
source.Bind( Name => target.Name);
Run Code Online (Sandbox Code Playgroud)
我很确定我可以处理前三个(尽管可以随意包含这些更改)但我不知道如何使用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 = …Run Code Online (Sandbox Code Playgroud) 我有一个方法,我想将此方法作为扩展方法添加到我的类的属性.此方法将表达式作为输入参数.方法如下:
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
我想像下面的例子一样使用这个方法:
string propertyName = MyClass.Property1.GetPropertyName();
Run Code Online (Sandbox Code Playgroud)
可能吗?如果是的话,解决方案是什么?