自动属性上的 INotifyPropertyChanged-Feature [英] INotifyPropertyChanged-Feature on Auto-Properties

查看:31
本文介绍了自动属性上的 INotifyPropertyChanged-Feature的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多实现 INotifyPropertyChanged-Interface 的模型类,以便在值更改时更新 UI.

I have many Model-Classes which implement the INotifyPropertyChanged-Interface in order to update the UI when value changed.

遗憾的是,必须完全编写属性才能支持此功能.我已经通过在 BaseClass 中使用 'SetPropertyValue'-Method() 减少了我的代码.

Sadly the properties must be written fully to support this feature. I decreased my code already by using the 'SetPropertyValue'-Method() in BaseClass.

private string _title;
public string Title 
{
    get { return title; }
    set { SetPropertyValue("Title", ref _title, value ); }
}

但是在一个文件中编写了 20 个这样的属性,与自动实现的属性不同,在短时间内理解文件的内容并不那么简单.

But with 20 properties written like that in one file it is not so simple to understand the content of the file in a short time unlike to the auto implemented properties.

我想要的是这样写我的属性:

What I want is to write my Property like this:

[NotifyChanged]
public string Title { get; set; }

我已经检查了 PostSharp 但在免费版本中只包含 10 个类(这是一个业余爱好项目,所以我不想花太多钱).

I checked already PostSharp but in the free version there are only 10 classes included (it's a hobby project so I don't want to pay much money).

是否有可能将我的一个逻辑附加到 C#-Compiler(作为预编译器)?我想在代码中的不同位置使用这样的功能,以减少不必要的编码行(尤其是自动属性).

Is there any possibility to attach my one logic to C#-Compiler (as a pre-compiler)? Such a feature I would like to use on different places in my code to reduce unneccessary coding lines (especially for auto-properties).

或者也许是一个 VisulStudio 扩展?

Or maybee a VisulStudio-Extension?

推荐答案

尝试 Fody.它是使用专用 msbuild 任务在构建过程中修改 IL 代码的库.

Try Fody. It is library which modifies IL code during build process using dedicated msbuild task.

它有大量的插件,包括 PropertyChanged,应该适合您的场景.该插件为您提供了可应用于类的属性ImplementPropertyChanged.然后 Fody 将生成对所有自动属性实施 INotifyPropertyChanged 的​​代码.

It has large base of addins including PropertyChanged which should suit in your scenario. This addin gives you attribute ImplementPropertyChanged which you can apply to a class. Then Fody will generate code implementing INotifyPropertyChanged to all auto-properties.

第二个选项如果您拥有 ReSharper 版本 7 或更高版本.它具有重构功能,可以帮助您实现 INotifyPropertyChanges.例如,它可以将自动属性转换为实现接口的普通"属性.您可能不会完全满足您 - 这种方法可能对您很有趣,因为它不涉及额外的库和程序集修改.

Second option if you have ReSharper version 7 or higher. It has refactoring which can help you with implementation of INotifyPropertyChanges. For example it can transform auto-property to "normal" property implementing the interface. Thou it may not fully satisfy you - this approach may be interesting for you because it does not involve additional libraries and assembly modification.

这篇关于自动属性上的 INotifyPropertyChanged-Feature的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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