相关疑难解决方法(0)

Linq表达式和扩展方法获取属性名称

我正在看这篇文章,它描述了在POCO属性之间进行数据绑定的简单方法:数据绑定POCO属性

Bevan的评论之一包括一个简单的Binder类,可用于完成此类数据绑定.它对我需要的东西很有用,但我想实现Bevan为改进课程所做的一些建议,即:

  • 检查是否已分配源和目标
  • 检查sourcePropertyName和targetPropertyName标识的属性是否存在
  • 检查两个属性之间的类型兼容性

此外,鉴于按字符串指定属性容易出错,您可以使用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)

.net c# data-binding poco system.componentmodel

4
推荐指数
1
解决办法
8264
查看次数

获取属性名称的扩展方法

我有一个扩展方法来获取属性名称

public static string Name<T>(this Expression<Func<T>> expression)
{
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}
Run Code Online (Sandbox Code Playgroud)

我称之为

string Name = ((Expression<Func<DateTime>>)(() => this.PublishDateTime)).Name();
Run Code Online (Sandbox Code Playgroud)

这工作正常,并将我PublishDateTime作为字符串返回.

但是我对调用语句有一个问题,它看起来太复杂了,我想要这样的东西.

this.PublishDateTime.Name()
Run Code Online (Sandbox Code Playgroud)

有人可以修改我的扩展方法吗?

c# reflection extension-methods propertyinfo

4
推荐指数
2
解决办法
4596
查看次数