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

 

C# 自定义事件

上一篇:Photoshop打造唯美的青色草地美女图片


下一篇:CorelDRAW(CDR)运用矩形填充图案工具设计制作星云特效实例教程