我在将自定义事件从 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% 了解上面的代码在做什么,我自己正在努力解决这个问题,如果有人可以帮助我,我将非常感激。