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