gpt4 book ai didi

c# - 如何在 C# 6.0 中实现 INotifyPropertyChanged?

转载 作者:IT王子 更新时间:2023-10-29 04:36:50 24 4
gpt4 key购买 nike

this question 的答案已被编辑为在 C# 6.0 中,可以使用以下 OnPropertyChanged 过程实现 INotifyPropertyChanged:

protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

但是,从该答案中并不清楚相应的属性定义应该是什么。使用此构造时,C# 6.0 中 INotifyPropertyChanged 的​​完整实现是什么样的?

最佳答案

合并各种更改后,代码将如下所示。我用评论突出显示了更改的部分以及每个部分的帮助

public class Data : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
//C# 6 null-safe operator. No need to check for event listeners
//If there are no listeners, this will be a noop
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

// C# 5 - CallMemberName means we don't need to pass the property's name
protected bool SetField<T>(ref T field, T value,
[CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}

private string name;
public string Name
{
get { return name; }
//C# 5 no need to pass the property name anymore
set { SetField(ref name, value); }
}
}

关于c# - 如何在 C# 6.0 中实现 INotifyPropertyChanged?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35582162/

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