gpt4 book ai didi

c# - 是否可以将 Property Changed 实现为 Attribute?

转载 作者:行者123 更新时间:2023-11-30 13:26:23 24 4
gpt4 key购买 nike

我找到了 Property Changed Event 的实现,我可以在其中调用 Property changed 而无需 Web 中的属性名称。然后我用它构建了一个扩展方法,就在这里

public static void OnPropertyChanged(this INotifyPropertyChanged iNotifyPropertyChanged, string    propertyName = null)
{
if (propertyName == null)
propertyName = new StackTrace().GetFrame(1).GetMethod().Name.Replace("set_", "");
FieldInfo field = iNotifyPropertyChanged.GetType().GetField("PropertyChanged", BindingFlags.Instance | BindingFlags.NonPublic);
if (field == (FieldInfo) null)
return;
object obj = field.GetValue((object) iNotifyPropertyChanged);
if (obj == null)
return;
obj.GetType().GetMethod("Invoke").Invoke(obj, new object[2]
{
(object) iNotifyPropertyChanged,
(object) new PropertyChangedEventArgs(propertyName)
});
}

所以我可以这样调用属性更改:

private bool _foo;
public bool Foo
{
get { _foo; }
private set
{
_foo = value;
this.OnPropertyChanged();
}
}

但我想,如果我在使用 Property changed 时不必实现 Property 的 getter 和 setter 会更好。

现在有人知道如何将 OnPropertyChanged 方法作为属性实现吗,也许是使用 AOP?

这样 Auto-Property 就可以像这样用于 Property Changed:

[OnPropertyChanged]
public bool Foo {set;get;}

最佳答案

查看 Fody , 和 PropertyChanged加入。它将在编译后修改 IL,以添加代码来为您的属性引发 PropertyChanged 事件。它类似于 Lasse 的回答中提到的 PostSharp,但它是免费和开源的。

关于c# - 是否可以将 Property Changed 实现为 Attribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25200516/

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