日期:2014-05-19  浏览次数:20506 次

60分,被NEW关键字捞晕了!!两个new 的例中有什么不一样!
<1>
假如父类中的方法并不是virtual的,子类中的方法也就无法使用override关键字进行覆写,而使用new关键字对父类中的方法进行覆盖,覆盖后,父类的对象引用来引用子类的对象时,进行调用该同名方法,会调用父类的方法,虽然实际上引用的是子类的对象。

using   System;
using   System.Collections.Generic;
using   System.Text;

namespace   Hello
{
interface   IHello
{
void   sayHello();
}
class   Hello   :   IHello
{
public   virtual   void   sayHello()
{
Console.WriteLine( "Hello! ");
}
}
class   HelloLee   :   Hello
{
public   override   void   sayHello()
{
Console.WriteLine( "Hello   Lee! ");
}
}
class   HelloCoderLee   :   HelloLee
{
public   new   void   sayHello()
{
Console.WriteLine( "Hello   CoderLee! ");
}
}
class   Program
{
static   void   Main(string[]   args)
{
IHello   sayHello;
sayHello   =   new   HelloCoderLee();
sayHello.sayHello();
Console.ReadLine();
}
}
}

输出为:
Hello   Lee!


<2>
而我查看SDK文档:
使用   new   修饰符显式隐藏从基类继承的成员。
若要隐藏继承的成员,请使用相同名称在派生类中声明该成员,
并用   new   修饰符修饰它。

//   cs_modifier_new.cs
//   The   new   modifier
using   System;
public   class   MyBaseC  
{
      public   static   int   x   =   55;
      public   static   int   y   =   22;
}

public   class   MyDerivedC   :   MyBaseC  
{
      new   public   static   int   x   =   100;       //   Name   hiding
      public   static   void   Main()  
      {
            //   Display   the   overlapping   value   of   x:
            Console.WriteLine(x);

            //   Access   the   hidden   value   of   x:
            Console.WriteLine(MyBaseC.x);

            //   Display   the   unhidden   member   y:
            Console.WriteLine(y);
      }
}
输出
100
55
22


<3>
看msdn:

new   关键字可以显式隐藏从基类继承的成员。
隐藏继承的成员意味着该成员的派生版本将替换基类版本


现在有一问题:为什么 <1> 中是输出Hello   Lee!(父类)

而不是输出Hello   CoderLee!(子类)
new关键字不是说隐藏基类吗,
也就说调用子类


这个例子与 <2> 例有什么不同
为什么 <2> 例中调用的是子类的属性


顺便问一下,怎样才能理清new   的使用

------解决方案--------------------
多态的时候 new 方法就不起作用了

如果要被子类override那就要virtual

new 是不行的 实际上调用的还是父类的方法 这个没办法解决

只有在写父类的时候所有的方法都virtual一下
------解决方案--------------------
new一个是在调用的时候使用,这个就很简单了,就是实力化一个对象。

当new 出现在 类里面 public 前面的时候是不是就晕了呢?其实不用去管它。


> > 为什么 <1> 中是输出Hello Lee!(父类)

这个呢是因为编译的时候,调用的方法的内容就固定了,就是调用父类,不会考虑子类。

而另一种方法就是“动态”的,会考虑子类李重写的方法。

就是这个意思。感觉一下:)