c# - 如何从另一个静态类订阅一个类中的事件?
问题描述
在这种情况下有什么问题?当尝试订阅事件时,我有一个 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} ");
}
}
}
解决方案
问题是您的委托和侦听器方法的签名不匹配。
代表签名是
Action<int> Death(int id);
而监听器函数的签名是
void AddListener(int id)
要添加AddListener
到OnDeath
事件中,它必须返回一个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;
推荐阅读
- javascript - 通过 WebPack 将 Bootstrap 加载到 Wordpress 时,ReactJS 代码拆分导致错误
- google-apps-script - 获取值跳过错误
- swiftui - SwiftUI:API 调用后如何移动 MapPin?
- javascript - 跳过字符串的一部分并用正则表达式替换匹配
- android-studio - Android Studio 4.0.1 丢弃连接的设备
- c++ - 根据模板类型使类成员变量可选的非详细解决方案?
- javascript - 获取端点时,Spotify API 收到错误“未提供令牌”
- java - 什么客户端 Linux / Liberty / HttpComponents 配置可以防止请求被错误识别为小窗口攻击?
- python-3.x - 有人可以帮我找到一种方法将列表扩展到特定索引处的另一个列表吗?
- javascript - 使用 Extendscript (JavaScript) 逐步更改 Indesign Swatch