用于设置警报的 C# 简单事件处理程序

标签 c# visual-studio events event-handling

为什么下面一行“alarm.AlarmEvent += new AlarmEventHandler(alarm_Sound);”给我“非静态字段、方法或属性 'AlarmClock.Alarm.alarm_Sound(object, System.EventArgs)' 需要一个对象引用”

   public static void Main(string[] args)
    {
        Alarm alarm = new Alarm(new DateTime(2010, 4, 7, 23, 2, 0));
        alarm.Set();
        alarm.AlarmEvent += new AlarmEventHandler(alarm_Sound);            
    }

完整源代码在这里: Program.cs AlarmEventArgs

最佳答案

您的alarm_Sound 方法是一个实例方法,这意味着它只能在您的类的实例 上使用。
由于 Main 是一个 static 方法,它不与类的实例相关联,因此您不能在其中使用任何实例方法。

您需要通过将 static 关键字添加到其声明中,使您的 alarm_Sound 处理程序方法成为静态方法。

或者,您可以创建该类的一个实例,然后引用该实例的处理程序方法。

关于用于设置警报的 C# 简单事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2593988/

相关文章:

c# - 如何在 C# 中将字符串解析为 dateTime?

c# - 即使在 using 语句中,FileStream 也不会关闭

c++ - 如果有 std::thread,Visual Studio 2017 linux 无法编译

c# - 将扩展方法放在一个文件中还是多个文件中?

c# - PropertyChangedEventHandler 是如何工作的?

c# - 形成 KeyUp 和 KeyDown 事件来改变变量

c# - 显式空检查与空合并运算符的编译器评估?

c# - 在构建时将 C++ 结构转换为 C# 结构

c++ - CMake:将条件编译器标志添加到 Visual Studio 项目中

javascript - Node 读流: when does the streaming happen?