首页 > Windows开发 > 详细

C# 自定义事件

时间:2021-07-29 01:05:29      阅读:20      评论:0      收藏:0      [点我收藏+]
class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            person.Height = 165;
            person.HeightChanged += Person_HeightChanged;
            person.Height++;
            Console.ReadKey();
        }

        private static void Person_HeightChanged(object sender, PropertyChanged<int> e)
        {
            Console.WriteLine("旧的身高为" + e.LastProperty + "新的身高为" + e.NewProperty);
        }

        public class PropertyChanged<T> : EventArgs
        {
            public readonly T LastProperty;
            public readonly T NewProperty;

            public PropertyChanged(T last, T newProperty)
            {
                LastProperty = last;
                NewProperty = newProperty;
            }
        }

        public class Person
        {
            private int height;

            public int Height
            {
                get { return height; }
                set 
                {
                    var old = height;
                    var newHeight = value;
                    height = value;
                    OnHeightChanged(new PropertyChanged<int>(old, newHeight));
                }
            }


            public event EventHandler<PropertyChanged<int>> HeightChanged;

            protected virtual void OnHeightChanged(PropertyChanged<int> e)
            {
                if (HeightChanged != null)
                {
                    HeightChanged.Invoke(this, e);
                }
            }
        }

 

C# 自定义事件

原文:https://www.cnblogs.com/niaofei123/p/15072868.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!