简体   繁体   English

C#中参数的动态类型转换

[英]dynamic type casting in parameter in c#

I happen to see a code something like this. 我碰巧看到这样的代码。

function((dynamic) param1, param2);

When and why do we need this kind of dynamic type casting for parameters? 什么时候以及为什么需要这种类型的参数动态类型转换?

It can be used to dynamically choose an overload of function(...) based on the type of param1 at runtime, for example: 它可以用于在运行时根据param1的类型动态选择function(...)的重载,例如:

public static void Something(string x)
{
    Console.WriteLine("Hello");
}

public static void Something(int x)
{
    Console.WriteLine("Goodbye");
}
public static void Main()
{
    object x = "A String";

    // This will choose string overload of Something() and output "Hello"
    Something((dynamic)x);

    x = 13;

    // This will choose int overload of Something() and output "Goodbye"
    Something((dynamic)x);
}

So even though x is a reference to object , it will decide at runtime what overload of Something() to call. 因此,即使x是对object的引用,它也将在运行时决定要调用Something()重载。 Note that if there is no appropriate overload, an exception will be thrown: 请注意,如果没有适当的重载,将引发异常:

    // ...
    x = 3.14;

    // No overload of Something(double) exists, so this throws at runtime.
    Something((dynamic)x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM