如何分解表达式以满足泛型属性更改方法?

时间:2013-04-22 18:30:47

标签: c# expression inotifypropertychanged

我有一个实现INotifyPropertyChanged的基本EF实体类。

基本属性,Id是我的例子:

  /// <summary>
  /// Entity Id
  /// </summary>
  public int Id {
     get { return id; }
     set { SetValue<int>(() => (Id != value), (v) => id = v); } // < can this be simplified into a single call?
  }

...定义了SetValue:

  protected void SetValue<TValue>(Expression<Func<bool>> evalExpr, Action<TValue> set) {
     // Compile() returns a Func<bool>
     var doSetValue = evalExpr.Compile();

     if (doSetValue()) {
        var expr = evalExpr.Body as BinaryExpression;
        //  this is not compiling - how do I decompose the expression to get what I need?
        var propertyName = ((PropertyExpression)expr.Left).Name;
        var assignValue = (TValue)((ConstantExpression)expr.Right).Value;

        set(assignValue);
        _propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));
     }
  }

我能找到的所有样品都是期望的参数。我更喜欢setter(SetValue调用)尽可能简单 - 也就是说,有没有办法将输入参数减少到1?

2 个答案:

答案 0 :(得分:1)

有各种各样的选项比你得到的更简单(这里有一些粗略的顺序,我喜欢每一个):

以下是“The .NET 4.5 Way”的核心代码片段:

protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
    if (object.Equals(storage, value)) return false;

    storage = value;
    this.OnPropertyChanged(propertyName);
    return true;
}

用过:

  /// <summary>
  /// Entity Id
  /// </summary>
  public int Id {
     get { return id; }
     set { SetValue(ref id, value); }
  }

答案 1 :(得分:1)

你应该改变

var propertyName = ((PropertyExpression)expr.Left).Name;

var propertyName = ((MemberExpression)expr.Left).Member.Name;

并且您的代码会编译,但您正在做的事情并非最佳和信任。你会得到一个InvalidCastException

在每次调用时编译Expression<T>都不是最佳的,并且,如何判断用户是否将lambda传递给方法,如:

() => (Id != value)

而不是

() => (id != value) // using the field instead of property

() => (value != Id) // passing the property as the second operand

此外,表达式中的value不是ConstantExpressionvalue本身只是属性的set部分的局部变量,当传递给lambda表达式时,会被提升为类字段(捕获值 - 请参阅here欲获得更多信息)。所以你所拥有的是双方的MemberExpression

如果您不能使用.NET 4.5([CallerMemberName]):

,我强烈建议您使用此方法
public class EntityBase : INotifyPropertyChanged
{
    protected virtual void OnPropertyChanged(string propName)
    {
        var h = PropertyChanged;
        if (h != null)
            h(this, new PropertyChangedEventArgs(propName));
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected bool ChangeAndNofity<T>(ref T field, T value, Expression<Func<T>> memberExpression)
    {
        if (memberExpression == null)
        {
            throw new ArgumentNullException("memberExpression");
        }

        var body = memberExpression.Body as MemberExpression;
        if (body == null)
        {
            throw new ArgumentException("Lambda must return a property.");
        }

        if (EqualityComparer<T>.Default.Equals(field, value))
        {
            return false;
        }

        field = value;
        OnPropertyChanged(body.Member.Name);
        return true;
    }
}

使用它很简单:

public class Person : EntityBase
{
    private int _id;
    public int Id
    {
        get { return _id; }
        set { ChangeAndNofity(ref _id, value, () => Id); }
    }
}