Csharp/CSharp Tutorial/Class/static constructor

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Static constructor 2

<source lang="csharp">using System; class MyClass {

  private static Random RandomKey;
  static MyClass()                     
  {
     RandomKey = new Random();                   
  }
  public int GetValue()
  {
     return RandomKey.Next();
  }

} class Program {

  static void Main()
  {
     MyClass a = new MyClass();
     MyClass b = new MyClass();
     Console.WriteLine("Next Random #: {0}", a.GetValue());
     Console.WriteLine("Next Random #: {0}", b.GetValue());
  }

}</source>

Next Random #: 1768997546
Next Random #: 1565321362

Static Constructors

<source lang="csharp">using System; class MyClass {

   static MyClass()
   {
       Console.WriteLine("MyClass is initializing");
   }
   public static int I;

} class MainClass{

   public static void Main()
   {
       MyClass.I = 1;
   }

}</source>

MyClass is initializing