我最近开始尝试使用PostSharp,我发现了一个特别有用的方面来自动实现INotifyPropertyChanged.你可以在这里看到这个例子.基本功能非常好(将通知所有属性),但有时我可能想要禁止通知.
例如,我可能知道特定属性在构造函数中设置一次,并且永远不会再次更改.因此,无需为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;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
972 次 |
| 最近记录: |