如何订阅到前pression树内的对象的事件? [英] How do I subscribe to an event of an object inside an expression tree?

查看:144
本文介绍了如何订阅到前pression树内的对象的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,我不能想到一个更好的标题。这是一个问题的两个部分,只有有意义起来。

Sorry I couldn't think of a better title. This is a two part question that only make sense together.

说我有这样的构造

public Fact(INotifyPropertyChanged observable, Func<bool> predicate)
{
	this.predicate = predicate;
	observable.PropertyChanged += (sender, args) =>
                     PropertyChanged(this, new PropertyChangedEventArgs("Value"));

}

这是如何使用它

and this is how it's used

new Fact(Model.AllowEditing, () => Model.AllowEditing);

在这里AllowEditing是一种INotifyPropertyChanged的的

where AllowEditing is a type of INotifyPropertyChanged

我想重构构造成

public Fact(Expression<Func<bool>> expression)

所以可以这样调用

So it can be call like this

new Fact(() => Model.AllowEditing);

现在的问题是如何解析的EX pression得到观察到的出前pression树,然后订阅其事件?

The question is how to parse that expression to get "observable" out of the expression tree then subscribe to its event?

在code以上不是我的,它来自从Ayende的例子最近的例子,这里是喜欢完整源$ C ​​$ C,如果有人想利用怎样的事实类正在使用的外观 http://github.com/ayende/Effectus

The code above is not mine, it come from an example recent example from Ayende, here is the like to the full source code if anyone want to take a look of how the Fact class is being used http://github.com/ayende/Effectus

推荐答案

基本上,你需要在这种情况下,对象存储在EX pression.Body.Ex pression。您需要编译和执行的前pression树来得到它。此外,您可能需要检查的类型是否真正实现你的接口和predicate是否是你的真正所期待的。

Basically, the object you need in this case is stored in expression.Body.Expression. You will need to compile and execute an expression tree to get it. Also, you will probably need to check whether the type really implements your interface and whether the predicate is what your really are looking for.

下面是一个非常粗略的code:

Here is a very rough code:

public Fact(Expression<Func<bool>> predicate)
{        
    this.predicate = predicate;
    MemberExpression body = predicate.Body as MemberExpression;

    // Check that you get a valid lambda expression, 
    // like object.Member, not something like !object.Member
    if (body == null) 
         throw new ArgumentException("'" + predicate + "': is not a valid expression for this method");
    var type = body.Expression.Type;

    // Check if type implements INotifyPropertyChanged using reflection  
    // ...

    INotifyPropertyChanged observable = 
    Expression.Lambda<Func<INotifyPropertyChanged>>(body.Expression).Compile()();
    //...
}

这篇关于如何订阅到前pression树内的对象的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆