C# 中的方法重载和动态关键字
我还没有升级到 4.0,否则我会自己检查代码片段。但我希望有专家能够对此发表评论。
在下面的代码中,是否会在运行时调用适当的 Print()
方法?在 C# 2010 中这样称呼它是否合法?
public void Test()
{
dynamic objX = InstantiateAsStringOrDouble();
Print(objX);
}
public void Print(string s)
{
Console.Write("string");
}
public void Print(double n)
{
Console.Write("double");
}
谢谢!
I still haven't upgraded to 4.0 else I would have checked the code snippet myself. But I hope some expert can comment on this.
In following code, will the appropriate Print()
method be called at runtime? Is it even legal in C# 2010 to call it that way?
public void Test()
{
dynamic objX = InstantiateAsStringOrDouble();
Print(objX);
}
public void Print(string s)
{
Console.Write("string");
}
public void Print(double n)
{
Console.Write("double");
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这确实有效。它将在运行时检查动态的使用情况并调用适当的方法,但是您几乎会丢失所有编译时检查,因此我要确保这确实是您想要做的。
Yes, that does in fact work. It will check the usage of the dynamic at runtime and call the appropriate method, however you lose almost all of your compile-time checking, so I'd make sure that's really what you'd want to do.
是的,你甚至可以这样做:
或者
它会按预期工作。
Yes, and you can even do this:
or
and it will work as expected.