2011-10-12 121 views
5

我碰巧看到這樣的代碼。動態類型鑄造參數在c#

function((dynamic) param1, param2); 

何時以及爲什麼我們需要這種動態類型鑄造參數?

+0

我希望看到更多。一般來說,如果該函數需要一個動態變量,您可以*執行,但這不是必需的。 – scottm

+0

@scottm:這就是我最初的想法,然後我記得你也可以在運行時使用它來選擇正確的方法重載。 –

+0

@JamesMichaelHare非常小的用例。這是我會譴責以前的開發者故意使用的一種東西。 – scottm

回答

5

它可以用來動態地選擇基礎上的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); 
} 

因此,即使xobject一個參考,它會在運行時決定什麼過載Something()來電。請注意,如果沒有適當的超載,將拋出異常:

// ... 
    x = 3.14; 

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