Java教程

事件

本文主要是介绍事件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

 

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)));
                }
            }
        }
    }
}

  

这篇关于事件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!