method overloading and dynamic keyword in C#

空扰寡人 提交于 2019-12-20 02:27:18

问题


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!


回答1:


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.




回答2:


Yes, and you can even do this:

public dynamic InstantiateAsStringOrDouble() { return 0.5; }

or

public dynamic InstantiateAsStringOrDouble() { return "hello"; }

and it will work as expected.



来源:https://stackoverflow.com/questions/5835989/method-overloading-and-dynamic-keyword-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!