2013-03-03 46 views
0

可以使用C#中的動態參數數量創建方法嗎?創建具有動態參數數量的方法

例如

Public void sum(dynamic arguments//like JavaScript) 
{ 
    //loop at run-time on arguments and sum 
} 

我可以使用動態對象?

+1

你在尋找'params'嗎? bla(params int [] variableInts) – bas 2013-03-03 18:35:09

+1

這個怎麼樣:https://www.google.com/search?btnG = 1&pws = 0&q = method + with + dynamic + number + of + parameter + c%23 – antonijn 2013-03-03 18:37:31

+1

如果你發佈了一個如何調用方法的例子,那真的會有所幫助。 – 2013-03-03 18:42:33

回答

4

使用params keyword實現了可變數量的參數。

params關鍵字可以讓你指定一個方法參數,該參數需要一個可變數量的參數 。您可以發送參數聲明中指定類型的參數 的逗號分隔列表,或者指定類型的參數數組 。您也可以不發送 參數。

例如:public void Sum(params int[] args){ }

我可以使用動態對象?

是的,但可能不是你想的方式。

// example 1 - single parameter of type dynamic 
private static void Sum(dynamic args) { } 

// will not compile; Sum() expects a single parameter whose type is not 
// known until runtime 
Sum(1, 2, 3, 4, 5); 

// example 2 - variable number of dynamically typed arguments 
private static void Sum(params dynamic[] args) { } 

// will compile 
Sum(1, 2, 3, 4, 5); 

所以,你可以有一個方法,如:

public static dynamic Sum(params dynamic[] args) { 

    dynamic sum = 0; 

    foreach(var arg in args){ 
     sum += arg; 
    } 

    return sum; 
} 

,並調用它:Sum(1, 2, 3, 4.5, 5)。 DLR足夠聰明,可以從參數中推斷出正確的類型,返回值將爲System.Double但是(至少在Sum()方法的情況下),放棄對類型規範和丟失類型安全的顯式控制似乎是一個壞主意。

我假設你有沒有使用Enumerable.Sum()

+0

我可以使用動態嗎? – 2013-03-03 18:36:17

+0

當您要等到運行時解析類型時才使用'dynamic'; sum方法意味着你*知道類型。 – 2013-03-03 18:37:28

+0

'private static void Sum(params dynamic [] args)'會編譯,如果這就是你要求的。 – 2013-03-03 18:38:22

2

也許一個例子單元測試澄清事情稍微有原因的:

[Test] 
    public void SumDynamics() 
    { 
     // note that we can specify as many ints as we like 
     Assert.AreEqual(8, Sum(3, 5)); // test passes 
     Assert.AreEqual(4, Sum(1, 1 , 1, 1)); // test passes 
     Assert.AreEqual(3, Sum(3)); // test passes 
    } 

    // Meaningless example but it's purpose is only to show that you can use dynamic 
    // as a parameter, and that you also can combine it with the params type. 
    public static dynamic Sum(params dynamic[] ints) 
    { 
     return ints.Sum(i => i); 
    } 

使用動態時,請注意,你告訴你的編譯器後退,所以你會在運行時得到你的異常。

[Test, ExpectedException(typeof(RuntimeBinderException))] 
    public void AssignDynamicIntAndStoreAsString() 
    { 
     dynamic i = 5; 
     string astring = i; // this will compile, but will throw a runtime exception 
    } 

瞭解更多關於dynamics

查看更多about params