C# 为什么在定义对象时不能添加事件?
我创建了一个带有后端CS的模板对象,如下所示:C# 为什么在定义对象时不能添加事件?,c#,xamarin,xamarin.forms,C#,Xamarin,Xamarin.forms,我创建了一个带有后端CS的模板对象,如下所示: public partial class GridTemplate : StackLayout { public event EventHandler Action; public GridTemplate() { InitializeComponent(); } public ICommand TapButtonPressed => new Command((object comp
public partial class GridTemplate : StackLayout
{
public event EventHandler Action;
public GridTemplate()
{
InitializeComponent();
}
public ICommand TapButtonPressed => new Command((object componentIdentifier) =>
{
this.Action?.Invoke(this, new EventArgs());
});
}
var cell = new GridTemplate
{
BackgroundColor = Color.White,
Text = row.Name,
Label = "ABC",
};
我可以在C中创建一个新对象,如下所示:
public partial class GridTemplate : StackLayout
{
public event EventHandler Action;
public GridTemplate()
{
InitializeComponent();
}
public ICommand TapButtonPressed => new Command((object componentIdentifier) =>
{
this.Action?.Invoke(this, new EventArgs());
});
}
var cell = new GridTemplate
{
BackgroundColor = Color.White,
Text = row.Name,
Label = "ABC",
};
但是我不能在{}
但是,我可以这样做:
cell.Action += openCategoriesPage;
有人能解释一下为什么我在构造对象时不能指定动作吗?首先,不允许您执行以下操作:
var cell = new GridTemplate
{
Label += "ABC"
};
cell.Action += openCategoriesPage; will become
cell.addAction(openCategoriesPage)
它与Label=Label+“ABS”相同-由于未构造对象,第二个标签尚不存在
关于事件,它们只是一种封装方式,当您执行+=时,将在后台生成的是对add方法的调用,类似于:
var cell = new GridTemplate
{
Label += "ABC"
};
cell.Action += openCategoriesPage; will become
cell.addAction(openCategoriesPage)
而且您不能在{}用法中调用方法,因为对象尚未构造
您可以通过CLR Book在C#中阅读有关事件的更多信息。您不是在“分配操作”,而是在向事件添加EventHandler委托。运算符为+=
,在VB中转换为AddHandler
。可能重复的