Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么在定义对象时不能添加事件?_C#_Xamarin_Xamarin.forms - Fatal编程技术网

C# 为什么在定义对象时不能添加事件?

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

我创建了一个带有后端CS的模板对象,如下所示:

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
。可能重复的