2010-07-08 21 views
-1

我想知道如何直接在參數括號聲明新的變量,並把它傳遞這樣的:C#創建和方法調用傳遞可變的直

MethodA(new int[]) //but how to fill the array if declared here? E.g. how to declare and set string? 


MethodA(int[] Array) 
... 

,以及如果需要申報對象(具有構造函數參數的類)?仍然可以在參數列表中?

+0

「如何聲明和設置字符串」:字符串是什麼? – 2010-07-08 10:06:10

+0

對不起,我的意思是當我只想傳遞字符串作爲參數。我可以這樣宣佈嗎? – Bornemix 2010-07-08 10:10:04

回答

2

你可以試試這個:

MethodA(new int[] { 1, 2, 3, 4, 5 }); 

這樣你達到你要求的功能。

似乎沒有辦法在參數列表中聲明一個變量;但是你可以使用一些慣用的伎倆就像調用它創建和初始化變量的方法:

int[] prepareArray(int n) 
{ 
    int[] arr = new int[n]; 
    for (int i = 0; i < n; i++) 
     arr[i] = i; 
    return arr; 
} 

... 
MethodA(prepareArray(5)); 
... 

隨着琴絃,爲什麼不直接使用字符串字面量:

MethodB("string value"); 

7
MethodA(new int[] { 1, 2, 3 }); // Gives an int array pre-populated with 1,2,3 

MethodA(new int[3]); // Gives an int array with 3 positions 

MethodA(new int[] {}); // Gives an empty int array 

你可以做字符串,對象等一樣的:

MethodB(new string[] { "Do", "Ray", "Me" }); 

MethodC(new object[] { object1, object2, object3 }); 

如果你想通過傳遞一個字符串到一個方法,這是你如何做到這一點:

MethodD("Some string"); 

string myString = "My string"; 
MethodD(myString); 

UPDATE: 如果你想通過一種方法來傳遞類,你可以做以下之一:

MethodE(new MyClass("Constructor Parameter")); 

MyClass myClass = new MyClass("Constructor Parameter"); 
MethodE(myClass); 
0

new int[0]new int {}將爲您工作。您也可以傳入值,如new int {1, 2, 3}。適用於列表和其他集合。

+0

而字符串呢? – Bornemix 2010-07-08 10:05:37

+0

'new string {「cat」,「dog」,「horse」}' - 沒問題。你也可以看一下'params' - 你可以在方法的末尾放置任意數量的參數,如string.Format中使用的那樣: 'public Thing DoMyThing(Thing aThing,params string [] moreArgs)'' – Lunivore 2010-07-08 13:17:04

+0

或者,使用你的例子:'MethodA(params int [] values)'可以被'MyClass.MethodA(1,2,3,4,5)調用' – Lunivore 2010-07-08 13:19:11

0

在你的情況,你會想聲明MethodB(string[] strArray)並把它作爲MethodB(new string[] {"str1", "str2", "str3" })

附: 我會建議你從C#教程開始,例如this之一。

0

你僅僅意味着:

MethodA("StringValue");

0

作爲一個方面說明:如果添加params關鍵字,你可以簡單地指定多個參數,它們將被包裝成自動數組:

void PrintNumbers(params int[] nums) 
{ 
    foreach (int num in nums) Console.WriteLine(num.ToString()); 
} 

然後可以稱爲:

PrintNumbers(1, 2, 3, 4); // Automatically creates an array. 
PrintNumbers(new int[] { 1, 2, 3, 4 }); 
PrintNumbers(new int[4]); 
相關問題