找回密码
 FreeOZ用户注册
查看: 2410|回复: 7
打印 上一主题 下一主题

[论坛技术] 懂C sharp的进来看看一个纯语言问题。

[复制链接]
跳转到指定楼层
1#
发表于 27-7-2011 20:56:35 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?FreeOZ用户注册

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

  5.     class MyClass : IMsg
  6.     {
  7.         public void Message()
  8.         {
  9.             Console.WriteLine("MyClass");
  10.         }
  11.     }

  12.     class MyDerivedClass : MyClass
  13.     {
  14.         public new void Message()
  15.         {
  16.             Console.WriteLine("MyDerivedClass");
  17.         }
  18.     }

  19.     class Program
  20.     {
  21.         static void Main(string[] args)
  22.         {
  23.             MyDerivedClass d = new MyDerivedClass();

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

  26.             Console.ReadKey(false);
  27.         }
  28.     }
复制代码
回复  

使用道具 举报

2#
发表于 27-7-2011 22:35:09 | 只看该作者
的确和书上的不一样,用msil看了看,各个函数头部的反汇编签名不太一样,可能原因在这里。LZ找到具体原因后来回帖哈
回复  

使用道具 举报

3#
发表于 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()
回复  

使用道具 举报

4#
发表于 27-7-2011 23:13:36 | 只看该作者
楼上正解
回复  

使用道具 举报

5#
发表于 28-7-2011 09:51:46 | 只看该作者
实际上我觉得作者是想说明“new”这个修饰词的作用。在这里因为new的message已经不同于myclass继承的interface Imsg了。你会发现d.message()的输出和m.message()的输出是不同的。
回复  

使用道具 举报

6#
 楼主| 发表于 28-7-2011 10:10:44 | 只看该作者
那确实是这个书上有错误咯?还第一次遇到有这么严重错误的书啊,这本书不敢看下去啦
回复  

使用道具 举报

7#
发表于 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".

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

使用道具 举报

8#
发表于 28-7-2011 13:07:26 | 只看该作者
感觉像是有关shadow method的。
http://stackoverflow.com/questio ... and-overriding-in-c

[ 本帖最后由 骷髅 于 28-7-2011 15:59 编辑 ]
回复  

使用道具 举报

您需要登录后才可以回帖 登录 | FreeOZ用户注册

本版积分规则

小黑屋|手机版|Archiver|FreeOZ论坛

GMT+10, 24-4-2024 21:20 , Processed in 0.023202 second(s), 25 queries , Gzip On, Redis On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表