开发者

Shared (static) classes with events in C#

开发者 https://www.devze.com 2022-12-24 16:02 出处:网络
Here is an example of what I would do in Visual Basic: Public Class Class1 Public Shared WithEvents Something As New EventClass

Here is an example of what I would do in Visual Basic:

Public Class Class1
    Public Shared WithEvents Something As New EventClass

    Public Shared Sub DoStuff() Handles Something.Test

    End Sub
End Class

Public Class EventClass
    Public Event Test()
End Class

How do I do this in C#?

I know there is not a Handles clause in C# so I need some function that is called and assign the event handlers there. However, since it's a sha开发者_运维技巧red class, there is no constructor; I must put it somewhere outside of a function.

How can it be achieved?


You can use the static constructor...

static readonly EventClass _something;

static Class1()
{
  _something = new EventClass();
  _something.Test += DoStuff;
}

static void DoStuff()
{
}


Try the following

public static class Class1 {
  private static EventClass something;
  public static EventClass Something {
    get { return something; }
  }
  static Class1 {
    something = new Class1();
    something.Test += DoStuff;
  }

  public static void DoStuff() {
    ...
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消