发现了个c# 的 bug

xmaxdong 2017-07-12 07:40:33
最近写接口的时候发现异常如下, 大家看看是不是bug


using System;

namespace ConsoleApplication1
{
interface A
{
void test(string s);
}

interface B : A
{
void test2(string s);
}

class C : B
{
public void test(string s)
{
Console.WriteLine(s);
}
public void test2(string s)
{
Console.WriteLine(s);
}
}

class Program
{
static void Main(string[] args)
{
string str = "here is a string";

dynamic str2 = str;

B instance = new C();

instance.test2(str); //正常
instance.test2(str2); //正常

instance.test(str); //正常
try
{
instance.test(str2); //异常
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

Console.ReadLine();
}
}
}
...全文
423 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
powerat123 2017-07-28
  • 打赏
  • 举报
回复
实测,确实报错, 原因是dynamic类型, 调用instance.test(str2); 时, str2不是string类型,而是dynamic, 它会去寻找接口B中 test(object str)方法, 而这个方法是不存在的, 所以把dynamic换成string 或者var 即可 , 具体原因请去查dynamic与var的区别,大致就是var是编译时会呗转成对应的类型,而dynamic不会,依旧是object
threenewbee 2017-07-13
  • 打赏
  • 举报
回复
我在线测试了下,没问题啊 http://ideone.com/M330jq 你报什么错误,你用的是C#什么版本?
xmaxdong 2017-07-13
  • 打赏
  • 举报
回复
引用 4 楼 caozhy 的回复:
[quote=引用 3 楼 xmaxdong 的回复:] [quote=引用 1 楼 caozhy 的回复:] 我在线测试了下,没问题啊 http://ideone.com/M330jq 你报什么错误,你用的是C#什么版本?
你到真实IDE试下再说[/quote] 和编译器有关系i,和ide没关系。你试试C# 5.0以上,应该没报错。[/quote] 大哥, 你试下再说啊.....
threenewbee 2017-07-13
  • 打赏
  • 举报
回复
引用 3 楼 xmaxdong 的回复:
[quote=引用 1 楼 caozhy 的回复:] 我在线测试了下,没问题啊 http://ideone.com/M330jq 你报什么错误,你用的是C#什么版本?
你到真实IDE试下再说[/quote] 和编译器有关系i,和ide没关系。你试试C# 5.0以上,应该没报错。
xmaxdong 2017-07-13
  • 打赏
  • 举报
回复
引用 1 楼 caozhy 的回复:
我在线测试了下,没问题啊 http://ideone.com/M330jq 你报什么错误,你用的是C#什么版本?
你到真实IDE试下再说
cy411129362 2017-07-13
  • 打赏
  • 举报
回复


才疏学浅,只能看IL想当然的给个解释。
大概相当于所有使用dynamic参数的方法都会被编译成单独的方法,在运行时用类似“反射”的技术去找,因为是B的instance调用的,所以会去B中找这个叫test的方法,于是找不到。
第一个test因为没有使用dynamic参数,没有经过额外处理,直接调用子类方法了。

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧