我在将自定义事件从vb.net转换为c#时遇到了一些问题,我真的没有vb.net的经验,而且我对这些自定义事件的经验更少,应用程序的其余部分转换没有太大问题,但是这一个让我卡住了。我用过的转换器(包括付费的和免费的)都不能产生可用的代码。
VB.net代码:<NonSerialized()> Private _objNonSerializablePropertyChangedHandlers As New System.ComponentModel.EventHandlerList
'''' <summary>
'''' Raised when a public property of this object is set.
'''' </summary>
Public Custom Event PropertyChanged As PropertyChangedEventHandler Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
AddHandler(ByVal value As PropertyChangedEventHandler)
Me.NonSerializablePropertyChangedHandlers.AddHandler(STR_PROPERTYCHANGEDEVENT, value)
End AddHandler
RemoveHandler(ByVal value As PropertyChangedEventHandler)
Me.NonSerializablePropertyChangedHandlers.RemoveHandler(STR_PROPERTYCHANGEDEVENT, value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As PropertyChangedEventArgs)
Dim obj As PropertyChangedEventHandler = TryCast(Me.NonSerializablePropertyChangedHandlers(STR_PROPERTYCHANGEDEVENT), PropertyChangedEventHandler)
If obj IsNot Nothing Then
obj.Invoke(sender, e)
End If
End RaiseEvent
我用c#编写的最好的代码如下:
c#[NonSerialized()]
private System.ComponentModel.EventHandlerList _objNonSerializablePropertyChangedHandlers = new System.ComponentModel.EventHandlerList();
public event PropertyChangedEventHandler PropertyChanged
{
add
{
this.NonSerializablePropertyChangedHandlers.AddHandler(STR_PROPERTYCHANGEDEVENT, value);
}
remove
{
this.NonSerializablePropertyChangedHandlers.RemoveHandler(STR_PROPERTYCHANGEDEVENT, value);
}
}
protected void OnPropertyChanged(string strPropertyName)
{
EventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler.Invoke(this, new PropertyChangedEventArgs(strPropertyName));
//PropertyChanged(this, new PropertyChangedEventArgs(strPropertyName));
}
}
然而,这会抛出一个错误"事件'CardBase。PropertyChanged'只能出现在+=或-="
的左侧行:EventHandler handler = this.PropertyChanged;
由于我不是100%对上面的代码是做什么,我正在努力修复这个自己,我会非常感激是有人可以帮助这。
更改此代码
protected void OnPropertyChanged(string strPropertyName)
{
EventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler.Invoke(this, new PropertyChangedEventArgs(strPropertyName));
}
}
protected void OnPropertyChanged(string strPropertyName)
{
var handler =
this.NonSerializablePropertyChangedHandlers[STR_PROPERTYCHANGEDEVENT]
as EventHandler;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(strPropertyName));
}
}
reference -event-只能出现在+=或-=的左侧