gpt4 book ai didi

c# - 使用属性抑制 PostSharp 多播

转载 作者:太空狗 更新时间:2023-10-29 21:25:33 25 4
gpt4 key购买 nike

我最近开始尝试使用 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);
}
}

关于c# - 使用属性抑制 PostSharp 多播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2397280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com