简体   繁体   中英

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:

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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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