在C#中方法重载和动态关键字关键字、方法、动态

2023-09-07 09:27:12 作者:深居我梦

我还没有升级到4.0要不我就检查了code片断自己。但我希望有专家能对此发表评论。

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.

在以下code,将相应的打印()方法被调用运行?它甚至在C#2010法律来调用它呀?

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");
}

谢谢!

推荐答案

是的,这是实际可行的。它会检查动态的使用在运行时,并调用适当的方法,但是你失去了几乎所有的编译时检查,所以我会确保这真的是你想要做的事情。

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.