[英]Raise event c# gives error: No overload matches delegate EventHandler
我正在尝试使某件事发生时引发事件。 因此,包含对引发事件的类的引用的其他类将得到通知。 这是到目前为止我得到的:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DropArea : MonoBehaviour {
public event EventHandler ObjectChange;
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider other)
{
var correctType = FindParentWithComponent(other.gameObject);
if (correctType != null)
{
var cc = correctType.GetComponent<Object_properties>();
if(cc.VariableTypeSelector == AcceptedVariableType)
{
DetectedObjectChange(null); // here i want to raise the event
}
}
}
protected virtual void DetectedObjectChange(EventArgs e)
{
EventHandler handler = ObjectChange;
if (handler != null)
{
handler(this, e );
}
}
}
这是应该通过引发事件通知的类:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IfStatement : MonoBehaviour {
public DropArea Base, Check, Increment;
void Start()
{
Base.ObjectChange += OnBaseObjectChange; //this line gives me an error so i cant compile.
}
// Update is called once per frame
void Update () {
}
void OnBaseObjectChange(System.Object sender)
{
Debug.Log("event is raised by element");
}
}
这是我得到的错误:
'OnBaseObjectChange'没有重载匹配委托'EventHandler'
我以前从未处理过事件,但我真的不明白如何解决此问题。 遗憾的是,我也不太了解有关事件的Microsoft文档:(
如果需要进一步澄清,请告诉我!
真的很感谢所有帮助!
只需更改此方法即可。 因为您的活动还需要EventArgs
void OnBaseObjectChange(System.Object sender, EventArgs e)
{
Debug.Log("event is raised by element");
}
代表持有方法的签名。 如您所见,事件的方法类型带有两个参数。 尝试将其与单个参数一起使用会导致错误。
handler(this, e);
或者,您可以将事件的类型更改为其他类型。 例如,如果不想在事件中使用EventArgs
,则使用Action<System.Object>
来保留处理程序方法的当前签名:
public event System.Action<System.Object> ObjectChange;
void OnBaseObjectChange(System.Object sender)
{
Debug.Log("event is raised by element");
}
在哪里可以这样称呼:
handler(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.