首页 > 解决方案 > 如何从另一个静态类订阅一个类中的事件?

问题描述

在这种情况下有什么问题?当尝试订阅事件时,我有一个 CS0407:'return-type method' 的返回类型错误; 骨架.OnDeath += Beholder.AddListener;

但我无法弄清楚错误在哪里。动作返回无效。并且签名中的参数是 int。在 AddListener - 也是。

namespace Tasks7 {
    class Program {
        static void Main() {
            Skeleton skeleton = new Skeleton();
            skeleton.OnDeath += Beholder.AddListener;
            Console.ReadKey();
        }
    }

    class Skeleton {
        public static int lastID = 0;
        public int id = 0;
        public delegate Action<int> Death (int id);
        public event Death OnDeath;
        public Skeleton() {
            this.id = lastID++;
        }
        public void Kill() {
            OnDeath?.Invoke(this.id);
        }
    }

    static class Beholder {
        public static void AddListener(int id) {
            Console.WriteLine($"{id} ");
        }
    }
}

标签: c#events

解决方案


问题是您的委托和侦听器方法的签名不匹配。

代表签名是

Action<int> Death(int id);

而监听器函数的签名是

void AddListener(int id)

要添加AddListenerOnDeath事件中,它必须返回一个Action<int>.

但我怀疑真正发生的事情是您误解了委托声明语法。

public delegate Action<int> Death(int id);

这声明了一个新的委托类型,它接受一个整数参数并返回一个Action<int>. 要使其与该AddListener方法兼容,只需将返回类型从 更改Action<int>void


注意:Action<int>它本身已经是一个委托类型,因此您可以Death完全废弃委托,而是Action<int>在事件处理程序声明中使用,如下所示:

public event Action<int> OnDeath;

推荐阅读