---
title: "一道静态构造函数的题目"
author: "devilhand"
date: "2009-12-23T00:00:27Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2009-12-23T00:00:27Z"
id: 554249
url: "https://devilhand.iteye.com/blog/554249"
---

```java

using System;
class A
{
    public static int X;
    static A()
    {
        X = B.Y + 1;
    }
}
class B
{
   public static int Y = A.X + 1;
   static B() { Console.WriteLine("{0}", Y); }  
   static void Main()//程序入口点在这里提高了类B的优先级
   {
      Console.WriteLine("{0},{1}", A.X, B.Y);
       
       Console.ReadLine();
   }
}

```

程序入口点在类B中提高了类B的优先级，即先执行类B的public static int Y = A.X + 1;再执行其中A.X调用了 static A()，再执行构造函数static B() 所以结果为：
2
1， 2

程序入口点在类B外面：

```java

using System;
class A
{
    public static int X;
    static A()
    {
        X = B.Y + 1;
    }
}
class B
{
   public static int Y = A.X + 1;
   static B() { Console.WriteLine("{0}", Y); }
}

class C
{
    static void Main()
    {       
        Console.WriteLine("{0},{1}", A.X, B.Y);       
        Console.ReadLine();
    }
}

```

此时，根据 Console.WriteLine("{0},{1}", A.X, B.Y); 先执行A.X即调用static A()而 X = B.Y + 1;中的B.Y调用了class B所以执行public static int Y = A.X + 1再执行static B() 然后执行  X = B.Y + 1;结果为：
1
2，1
若为：Console.WriteLine("{0},{1}", B.Y, A.X);先执行public static int Y = A.X + 1;其中A.X调用了static A()再执行static B() ，结果为
2
2，1