c# – 使用Attribute抑制PostSharp组播
发布时间:2020-12-15 08:13:25 所属栏目:百科 来源:网络整理
导读:我最近开始尝试使用PostSharp,我发现了一个特别有用的方面来自动实现INotifyPropertyChanged.您可以看到示例 here.基本功能非常出色(将通知所有属性),但在某些情况下我可能希望禁止通知. 例如,我可能知道特定属性在构造函数中设置一次,并且永远不会再次更改.
我最近开始尝试使用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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |