阅读 93

C# 自定义事件

C# 自定义事件

复制代码

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

复制代码

来源https://www.cnblogs.com/niaofei123/p/15072868.html

文章分类
后端
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐