簡體   English   中英

引發事件C#給出錯誤:沒有重載匹配委托EventHandler

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM