如何在不进行显式调用的情况下实现属性已更改的通知? [英] How to implement a property changed notification without making an explicit call?

查看:96
本文介绍了如何在不进行显式调用的情况下实现属性已更改的通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中有一个双向数据绑定的概念,当一个对象属性值在数据库中被更新时,框架还会在 INotifyPropertyChanged 接口被实现。



我在C#中寻找这样的功能,但不使用WPF。



这种情况是,当一个对象属性被更新时,一系列通知被发送给这个对象的其他消费者,通知他们属性改变。



所以流程是:


  1. 更新数据库

  2. 通知消费者1

  3. 通知消费者2

此过程需要三行。有没有办法实现一个属性的WPF概念更改为更新消费者(比如事件驱动),而不需要明确通知消费者?

解决方案

当实现 INotifyPropertyChanged 时,只是想让消费者知道属性已经改变时,



如果你想要实现的是减少样板代码,也就是说,每个设置器只有一行代码,您可以查看这个简单的解决方案,其中可以更好地与C# 5


In WPF there is the concept of two-way data binding, where when an object property value is updated in the db, it the framework also updates the view when the INotifyPropertyChanged interface is implemented.

I'm looking for something like this functionality in C# but not using WPF.

The scenario is that when an object property is updated, a series of notifications are sent to the other consumers of this object, notifying them of the property change.

So the flow is:

  1. Update the database
  2. Notify consumer 1
  3. Notify consumer 2

This process requires three separate lines. Is there a way to implement the WPF concept of a property changed to update whoever the consumers are (say, event-driven) without needing to explicitly notify the consumers?

解决方案

When implementing INotifyPropertyChanged, you are simply raising an event whenever you want to let consumers know that the property has changed. You only make one call to raise the event regardless of how many consumers are listening to that event.

If what you're trying to achieve is reduce boilerplate code, i.e. have only one line of code per setter, you can have a look at this simple solution, which can be made even nicer with C# 5.

这篇关于如何在不进行显式调用的情况下实现属性已更改的通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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