![](/img/trans.png)
[英]C# Dynamic casting surpasses the type mismatch error for a different parameter
[英]dynamic type casting in parameter in c#
我碰巧看到這樣的代碼。
function((dynamic) param1, param2);
什么時候以及為什么需要這種類型的參數動態類型轉換?
它可以用於在運行時根據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);
}
因此,即使x
是對object
的引用,它也將在運行時決定要調用Something()
重載。 請注意,如果沒有適當的重載,將引發異常:
// ...
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.