是否有类似于事件的Null条件运算符.按钮单击+=(ss,ee)



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

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

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条件运算符。它接受null?http://prntscr.com/pv1inc

问题与事件无关。

null条件运算符用于在引用为null时停止求值。

它不适用于任务的左侧或右侧部分。

如果您有:

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

你不能写:

Test v;
v?.Value = 10;
int a = v?.Value;

因为如果v为null,则不计算v.值。

  • 那么该如何处理= 10呢?

  • 或者a该怎么办?

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

C#事件为空

因此编译器错误地禁止了这样的写入。

这就是为什么你不能写:

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

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

你可以说你想要编译器忽略这一点。

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

我们可以写的是:

v?.Test();

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

int a = v?.Value ?? 0;

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

空条件运算符?。和[]

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

事件只不过是一个围绕Delegate的Add((和Remove((访问器。然而,可能有点令人困惑的是,类代码可以在Event名称下完全访问它(read、nulling、etic(。

给他们打电话的方式是这样的。我以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

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

EventHandler handler = myEvent;
handler?.Invoke(args);

最新更新