首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

一个简单的C#有关问题

2011-12-28 
一个简单的C#问题?//源码如下:using Systemusing System.Collections.Genericusing System.Textnamespa

一个简单的C#问题?
//源码如下:
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
  using System;

  public class A
  {
  public void F()
  {
  Console.WriteLine("A.F()");
  }
  }

  class B : A
  {
  private A a;
  public B()
  { }
  public B(A a)
  {
  this.a = a;
  }
  public new void F()
  {
  a.F();
  }
  }

  class Test
  {
  public static void Main()
  {
  B b1 = new B();
  B b2 = new B(b1);
  b2.F();

  Console.Read();
  }
  }  
}

//输出结果是:A.F()

为什么会调用到父类的F()方法呢?????

[解决办法]
B b2=new B(b1);//b2.a指向的是b1.a
b2.F()调用b2.a.F();
当然是调用了父类的方法了
[解决办法]
并不是因为B是A的子类
而是因为你在B中定义了一个A类的变量a
输出“A.F()”的是a这个变量
跟父类没有关系
[解决办法]

C# code
//源码如下: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 {     using System;     public class A     {         public void F()         {             Console.WriteLine("A.F()");         }     }     class B : A     {         private A a;         public B()         { }         public B(A a)         {             this.a = a;         }         [color=#FF0000]public new void F()         {             a.F(); //这个调用什么?你看清楚        } [/color]    }     class Test     {         public static void Main()         {             B b1 = new B();             B b2 = new B(b1);             b2.F();             Console.Read();         }     }      } 

热点排行