C#基础知识-接口如何工作并调用实现的接口

时间:2018-12-24 19:44:56

标签: c# unity3d

我迫切需要有人向我解释以下案件及其在幕后的运作方式。这将帮助我更深入地理解该概念。

统一案例:

在Unity3D引擎中,如果我们要检测对UI元素的单击,我们只需对自定义类实施其预制的接口之一,即“ IPointerClickHandler”。

public void OnPointerClick(PointerEventData eventData)
{

  // Do whatever you want in here, when you detect click on UI element
}

该脚本需要附加到每个单独的元素上,但最终,它就像一个超级魅力。

我的案子:

这让我着迷,因为我不确定Unity如何知道我的类实现了其接口之一并调用适当的方法。

我想做类似的把戏,但我不知道怎么做。例如,我想通知所有实现“ IScore”侦听器的类,该类具有方法“ OnScoreChanged(float newScore)”;

public float Score;

public interface IScore {

    void OnScoreChanged(float newScore);
}



public void SetScore(int newScore) {

    Score = newScore;
   //Notify all classes that implement IScore interface

   // .OnScoreChanged(newScore);
}``

我可能需要引用,所以我的想法是获取对实现“ OnScoreChanged”的类的所有引用。上面的示例是正确的方法吗?如何使它起作用?基本上,我想在需要获得新分数通知的类中实现此接口,而完全忘记如何调用此方法。这样可能吗?

    public class MyClassB: IScore {
        public void OnScoreChanged(float newScore)
        {
            // This just got called after score 
//changed..and without any additional implementation!
        }
    }

PS,我知道我可以将委托与事件一起使用(然后从其他类中订阅该事件),但是我很好奇Unity如何才能仅调用接口方法并使代码更整洁(因此用户不会这样做)。 t订阅其事件等)。

1 个答案:

答案 0 :(得分:1)

一种自己实现的方法是从单个基类派生所有类。该基类将调用VIRTUAL函数class User(models.Model): ... def save(self, **kwargs): self.password = make_password(self.password) return super(User, self).save(**kwargs) 。 [注意:您所有的自定义Unity组件类都源自Monobehavior。]

然后,当您创建派生类时,只需使用特定于该组件的版本覆盖虚拟make_password函数即可。


但是,如果您只想保留接口:现在可以使用OnWhatever()OnWhatever()并为要查找的类型指定 Interface 。通过在所有场景的"root" Objects上调用GetComponents < T >函数,可以在界面搜索中甚至更“宽”。

然后,您只需为所有GetComponentsInChildren < T >结果调用/调用指定的GetCompoentsInChildren < T > ()函数接口。