viewpl 发表于 27-7-2011 20:56:35

懂C sharp的进来看看一个纯语言问题。

看了一本书:
Effective C# 50 Specific Ways to Improve Your C# Second Edition
Bill Wagner
上面 Item 23: Understand How Interface Methods Differ from Virtual Methods
的例子程序执行结果和书上描述截然相反。有点搞懵了,是不是这本书很烂,还是我哪里搞错? interface IMsg
    {
      void Message();
    }

    class MyClass : IMsg
    {
      public void Message()
      {
            Console.WriteLine("MyClass");
      }
    }

    class MyDerivedClass : MyClass
    {
      public new void Message()
      {
            Console.WriteLine("MyDerivedClass");
      }
    }

    class Program
    {
      static void Main(string[] args)
      {
            MyDerivedClass d = new MyDerivedClass();

            IMsg m = d as IMsg;
            m.Message(); // 书上说这里会打印"MyDerivedClass",而实际运行结果是"MyClass"

            Console.ReadKey(false);
      }
    }

z37214728 发表于 27-7-2011 22:35:09

的确和书上的不一样,用msil看了看,各个函数头部的反汇编签名不太一样,可能原因在这里。LZ找到具体原因后来回帖哈 :P

katsura 发表于 27-7-2011 22:48:26

Surely public void Message() in MyClass should be decalred virtual
ie
public virtual void Message()

and overwritten in MyDerived class by
public override void Message()

woodheadz 发表于 27-7-2011 23:13:36

楼上正解
:lol

xyouc 发表于 28-7-2011 09:51:46

实际上我觉得作者是想说明“new”这个修饰词的作用。在这里因为new的message已经不同于myclass继承的interface Imsg了。你会发现d.message()的输出和m.message()的输出是不同的。

viewpl 发表于 28-7-2011 10:10:44

那确实是这个书上有错误咯?还第一次遇到有这么严重错误的书啊,这本书不敢看下去啦:funk: :funk:

jamesxiao72 发表于 28-7-2011 11:18:46

"Item 23: Understand How Interface Methods Differ from Virtual Methods"

程序里根本就没讲到Virtual, 也没override, 反而冒出一个new, 莫名其妙...难道是标题打错了得改成Interface Differ from "New" modifier? 不过interface和new还真没什么可联系的, new了以后只有明确定义使用那个new所在的class才会调用new的方法, 这里只是定义使用interface, 当然输出"MyClass".

不管怎样, 这本书还是不看为上啊.

骷髅 发表于 28-7-2011 13:07:26

感觉像是有关shadow method的。
http://stackoverflow.com/questions/392721/difference-between-shadowing-and-overriding-in-c

[ 本帖最后由 骷髅 于 28-7-2011 15:59 编辑 ]
页: [1]
查看完整版本: 懂C sharp的进来看看一个纯语言问题。