You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何正确为Employee类实现INotifyPropertyChanged接口

正确实现INotifyPropertyChanged的三个类方案

Employee类修正

你当前的Employee类只声明了PropertyChanged事件,但既没实现INotifyPropertyChanged接口,也没在属性变更时触发通知。修正后需要实现接口,将自动属性改为带私有字段的形式,在set方法中检查值变化并触发事件:

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class Employee : INotifyPropertyChanged
{
    private string? _name;
    private string? _position;
    private string? _phone;
    private string? _email;
    private string? _room;
    private string? _mainWorkplace;
    private string? _workplace;

    public string? Name
    {
        get => _name;
        set
        {
            if (_name != value)
            {
                _name = value;
                OnPropertyChanged();
            }
        }
    }

    public string? Position
    {
        get => _position;
        set
        {
            if (_position != value)
            {
                _position = value;
                OnPropertyChanged();
            }
        }
    }

    public string? Phone
    {
        get => _phone;
        set
        {
            if (_phone != value)
            {
                _phone = value;
                OnPropertyChanged();
            }
        }
    }

    public string? Email
    {
        get => _email;
        set
        {
            if (_email != value)
            {
                _email = value;
                OnPropertyChanged();
            }
        }
    }

    public string? Room
    {
        get => _room;
        set
        {
            if (_room != value)
            {
                _room = value;
                OnPropertyChanged();
            }
        }
    }

    public string? MainWorkplace
    {
        get => _mainWorkplace;
        set
        {
            if (_mainWorkplace != value)
            {
                _mainWorkplace = value;
                OnPropertyChanged();
            }
        }
    }

    public string? Workplace
    {
        get => _workplace;
        set
        {
            if (_workplace != value)
            {
                _workplace = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
  • 使用[CallerMemberName]特性可以自动获取属性名,避免手动拼写错误
  • 在set方法中先判断值是否真的变化,避免无意义的通知触发

EmployeeList类实现

ObservableCollection<Employee>本身已经实现了INotifyCollectionChanged和INotifyPropertyChanged,能自动通知集合的增、删、改操作。如果你的EmployeeList有自定义属性(比如搜索关键词、选中员工),需要为这些属性添加变更通知:

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

public class EmployeeList : ObservableCollection<Employee>, INotifyPropertyChanged
{
    private string? _searchKeyword;
    private Employee? _selectedEmployee;

    // 自定义搜索关键词属性,变更时触发搜索
    public string? SearchKeyword
    {
        get => _searchKeyword;
        set
        {
            if (_searchKeyword != value)
            {
                _searchKeyword = value;
                OnPropertyChanged();
                PerformSearch();
            }
        }
    }

    // 自定义选中员工属性
    public Employee? SelectedEmployee
    {
        get => _selectedEmployee;
        set
        {
            if (_selectedEmployee != value)
            {
                _selectedEmployee = value;
                OnPropertyChanged();
            }
        }
    }

    // JSON保存示例
    public void SaveToJson(string filePath)
    {
        // 实现JSON序列化逻辑,比如用Newtonsoft.Json或System.Text.Json
    }

    // JSON加载示例
    public void LoadFromJson(string filePath)
    {
        // 实现JSON反序列化逻辑,加载后更新集合
        Clear();
        // 假设加载得到employees列表
        // foreach (var emp in employees) Add(emp);
    }

    // 搜索逻辑示例
    private void PerformSearch()
    {
        // 根据SearchKeyword过滤集合,这里可以结合业务需求实现
    }

    public new event PropertyChangedEventHandler? PropertyChanged;

    protected new void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        base.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
  • 用new关键字覆盖事件和方法,确保自定义属性的通知能被外部订阅者捕获
  • 集合本身的变更(如Add、Remove)由ObservableCollection自动处理通知,无需额外代码

SearchResult类实现

SearchResult需要手动实现INotifyPropertyChanged,为其包含的结果列表、搜索条件等属性添加变更通知:

using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

public class SearchResult : INotifyPropertyChanged
{
    private List<Employee>? _results;
    private bool _hasResults;
    private string? _searchCriteria;

    public List<Employee>? Results
    {
        get => _results;
        set
        {
            if (_results != value)
            {
                _results = value;
                OnPropertyChanged();
                // 联动更新HasResults状态
                HasResults = _results?.Count > 0;
            }
        }
    }

    public bool HasResults
    {
        get => _hasResults;
        set
        {
            if (_hasResults != value)
            {
                _hasResults = value;
                OnPropertyChanged();
            }
        }
    }

    public string? SearchCriteria
    {
        get => _searchCriteria;
        set
        {
            if (_searchCriteria != value)
            {
                _searchCriteria = value;
                OnPropertyChanged();
            }
        }
    }

    // CSV保存示例
    public void SaveToCsv(string filePath)
    {
        // 实现CSV写入逻辑,比如逐行写入员工属性
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
  • 当Results属性变化时,自动更新HasResults并触发其通知,确保关联状态的变更能被正确感知

内容的提问来源于stack exchange,提问作者RealSteel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 12:13:12