我最近开始尝试使用PostSharp,我发现了一个特别有用的方面来自动实现INotifyPropertyChanged.您可以看到示例
here.基本功能非常出色(将通知所有属性),但在某些情况下我可能希望禁止通知.
例如,我可能知道特定属性在构造函数中设置一次,并且永远不会再次更改.因此,无需为NotifyPropertyChanged发出代码.当类不经常实例化时,开销很小,我可以通过从自动生成的属性切换到字段支持的属性并写入字段来防止问题.但是,当我正在学习这个新工具时,知道是否有办法用属性标记属性来抑制代码生成会很有帮助.我希望能够做到这样的事情:
[NotifyPropertyChanged] public class MyClass { public double SomeValue { get; set; } public double ModifiedValue { get; private set; } [Suppressnotify] public double OnlySetonce { get; private set; } public MyClass() { OnlySetonce = 1.0; } }
解决方法
您可以使用Methodpointcut而不是Multicastpointcut,即使用Linq-over-Reflection并针对PropertyInfo.IsDefined(您的属性)进行过滤.
private IEnumerable<PropertyInfo> SelectProperties( Type type ) { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public; return from property in type.GetProperties( bindingFlags ) where property.CanWrite && !property.IsDefined(typeof(Suppressnotify)) select property; } [OnLocationSetValueAdvice,Methodpointcut( "SelectProperties" )] public void OnSetValue( LocationInterceptionArgs args ) { if ( args.Value != args.GetCurrentValue() ) { args.ProceedSetValue(); this.OnPropertyChangedMethod.Invoke(null); } }
原文地址:https://www.jb51.cc/csharp/239000.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。