C# 6.0 (C# vNext) 新功能之:Event initializers
事件初始化(Event initializers)
在 C# 6.0 新增功能,可以在建構實例時,直接初始化事件處理函式,如下:
例一:
new Customer { Notify += MyHandler };
例二:
var client = new WebClient
{
DownloadFileCompleted += DownloadFileCompletedHandler
};
例三:
var button = new Button { ... Click += (source, e) => ... ... };
另一個例子,在宣告事件時,直接初始化
public virtual event EventArgs RoslynReleased = delegate { };
接下來比較一下,原本的寫法和新的寫法:
public class Person
{
private int _age;
public int Age
{
get
{
return _age;
}
set
{
_age = value;
OnAgeChanged(EventArgs.Empty);
}
}
public string Name { get; set; }
public event EventHandler AgeChanged;
protected virtual void OnAgeChanged(EventArgs e)
{
if (AgeChanged != null)
{
AgeChanged(this, e);
}
}
public override string ToString()
{
return string.Format("Name:{0}, Age:{1}", Name, Age);
}
}
以前的寫法:
var person = new Person { Age = 30, Name = "Calvin" };
person.AgeChanged += (s, e) => Console.WriteLine("Person:{0}", ((Person)s));
person.Age += 1;
新的寫法:
var person2 = new Person { Age = 30, Name = "Kelly", AgeChanged += (s, e) => Console.WriteLine("Person:{0}", ((Person)s)); };
person2.Age += 1;