using System;namespace ConsoleApplication1
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
new B();
Console.ReadLine();
}
}
class A
{
public A()
{
PrintFields();
}
public virtual void PrintFields(){}
}
class B:A
{
int x=1;
int y;
public B()
{
y=-1;
}
public override void PrintFields()
{
Console.WriteLine("x={0},y={1}",x,y);
}
}
}为什么会输出:
x=1,y=0 呢?

解决方案 »

  1.   

    执行顺序:0  new B();
    1  int x=1; 
        int y; 
    2 public A() 
      { 
       PrintFields(); 
      } 3
      public override void PrintFields() 
      { 
      Console.WriteLine("x={0},y={1}",x,y);  //此时x=1 y默认为0
      }

      public B() 
      { 
      y=-1; 
      } 
    5 Console.ReadLine(); 
    跟一遍代码就清楚了
      

  2.   

    4  
      public B()  
      {  
      y=-1;  
      }  在这里y=-1; 
    为何最后y=0?不是面试题
      

  3.   

    是顺序问题吧,先执行构造函数再执行int x=1; int y; 所以
      

  4.   

    B中的PrintFields是override的 调用基类构造函数后 
    public A()         
      {                             
          PrintFields();             
      }       
    所以这里调用的是B中的PrintFields,然后在执行y=-1,但已不产生任何输出了。
      

  5.   

    new B ()后,
    int x=1; 
    int y=0; 
    继而执行public B(),调用父类的构造函数,进而调用了父类的PrintFields方法(x=1,y=0);而子类中重写该方法输出x,y时,B本身的构造函数还未被执行,所以y=0