事件

当某个值发生变化时,将触发事件;

 

using System;
using System.ComponentModel;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //TestClassCSharp6 test = new TestClassCSharp6();
            //Console.WriteLine(test.Name);

            #region 事件
            NotfifyPropertyChanged notfifyPropertyChanged = new NotfifyPropertyChanged();

            notfifyPropertyChanged.PropertyChanged += NotfifyPropertyChanged_PropertyChanged;

            notfifyPropertyChanged.LastName = "SHa.Jazy";
            notfifyPropertyChanged.LastName = "SHa.Jazyfdasf";

            #endregion

        }

        private static void NotfifyPropertyChanged_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            Console.WriteLine($"值发生了变化!");
        }
    }


    public class NotfifyPropertyChanged : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string lastName;

        public string LastName
        {
            get => lastName;
            set
            {
                if (value != lastName)
                {
                    lastName = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(LastName)));
                }
            }
        }
    }
}

  

posted @ 2021-12-17 23:22  艾特-天空之海  阅读(14)  评论(0编辑  收藏  举报