0

为什么事件没有空条件运算符?

例如,如果对象不为空,我有以下代码引发事件:

Button TargetButton =  null;

    if(IsRunning)
    {
       TargetButton = new ....
    }

TargetButton?.Click +=(ss,ee)=>{...}

// Compile-time error 
// The event 'EditorButton.Click' can only appear on the left hand side of += or -= 

简要地 :

有其他选择吗?比平时使用if(TargetButton != null ) ... raise event

为什么事件没有空条件运算符。它接受 null 吗? http://prntscr.com/pv1inc

4

3 回答 3

3

该问题与事件无关。

如果引用为空,则空条件运算符将停止评估。

它不适用于作业的左侧或右侧。

如果你有:

public class Test
{
  public int Value;
  public void Method() { }
}

你不能写:

Test v;

v?.Value = 10;

int a = v?.Value;

因为如果 v 为 null,则不会评估 v.Value。

  • 那么该怎么办= 10呢?

  • 或者怎么办a

因此,在为空时为空的事件变量添加或删除事件处理程序时也是如此。

C# 事件为空

因此编译器错误不允许这样的写作。

这就是为什么你不能写:

TargetButton?.Click +=(ss,ee)=>{...}

因为(ss,ee)=>{...}如果TargetButton为空怎么办?

你可以说你希望编译器忽略它。

但是编译器不允许做这种不干净的事情。

我们可以写的是:

v?.Test();

这里是 v 是 null 方法没有被调用,一切都很好,因为编译器不知道该怎么做。

int a = v?.Value ?? 0;

这里如果 v 为空,则使用 0。

空条件运算符 ?. 和 ?[]

空合并运算符 ?? 和??=

于 2019-11-10T18:11:18.367 回答
0

事件只不过是包裹在委托周围的 Add() 和 Remove() 访问器。然而,有点令人困惑的是,类代码可以在事件名称下完全访问它(读取、归零、等)。

调用它们的方式如下所示。我以 INotifyPropertyChanged 为例:

//Declaring the event
public event PropertyChangedEventHandler PropertyChanged;  

//the function that raises the Events.
private void NotifyPropertyChanged(
//That attribute is almost unique for the function of NotifyPropertyChange
//It puts in teh propertyName if nothing is given
//You just use normal paramters here
[CallerMemberName] String propertyName = "")  
{  
    //Nullcheck, Invoke with EventArgs containing the propertyName
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}  

我确实记得一个旧信息,您应该将事件列表复制到局部变量中。我认为这与多任务处理或枚举器更改有关。

//volatile so Optimisations will not cut it out
volatile var localCopy = PropertyChanged
于 2019-11-10T18:11:09.893 回答
0

事件本身不为空。但是您可以创建一个处理程序并将其分配给事件。

EventHandler handler = myEvent;
handler?.Invoke(args);
于 2019-11-29T23:31:36.093 回答