C# 事件声明和调用:Action<string> Errer 事件详解
这是一个 C# 中声明事件的语法,它声明了一个名为 'Errer' 的事件,该事件将在发生错误时触发,并将一个字符串作为参数传递给事件处理程序。
要调用此事件,您需要创建一个事件处理程序,并使用 '+=' 操作符将其添加到事件的委托中。例如:
class MyClass {
public event Action<string> Errer;
public void DoSomething() {
// something goes wrong
if (somethingWrong) {
Errer?.Invoke('Something went wrong!');
}
}
}
// somewhere else in the code
MyClass myObject = new MyClass();
myObject.Errer += errorMessage => Console.WriteLine(errorMessage);
// when DoSomething() is called and an error occurs, the message will be printed to the console
myObject.DoSomething();
原文地址: https://www.cveoy.top/t/topic/mFHV 著作权归作者所有。请勿转载和采集!