2015-05-04 90 views
0

excelFilesNamesstring的陣列,在excelFilesNames中有1個以上的值。 打印oVariableName[2]值時打印"system.string"。我想通過將其分配給oVariableName[2]來打印所有excelFilesNames的值。如何通過分配字符串來訪問字符串數組的值?

的代碼如下

Object[] oVariableName = new object[3]; 
oVariableName[2] = excelFilesNames;  
MessageBox.Show(oVariableName[2].ToString()); 
+0

爲什麼不只是'MessageBox.Show(excelFilesNames [2]);'? –

回答

1
Object[] oVariableName = new object[3]; 
oVariableName[2] = string.Join(",", excelFilesNames);  
MessageBox.Show(oVariableName[2]); 

你並不需要使用Object[]雖然:

var fileNames = string.Join(",", excelFilesNames); 
MessageBox.Show(fileNames); 
1

如果excelFilesNames是一個字符串數組,具有foreach遍歷它:

Object[] oVariableName = new object[3]; 
oVariableName[2] = excelFilesNames; 

foreach (string s in oVariableName[2]) 
{ 
    MessageBox.Show(s); 
} 

注意我不確定爲什麼您將string[]分配給object[]內的object字段,但我會假設您的問題是需要完成的。

0

由於oVariableName[2]內容被稱爲是一個string[],你可以將它轉換爲string[]和利用string.Join()創建多串,每名一行,像這樣:

MessageBox.Show(string.Join("\n", (string[])oVariableName[2])); 

然而,這將在運行時爆炸,如果oVariableName[2]不是一個字符串數組。你可以抵禦這樣的:

var asStringArray = oVariableName[2] as string[]; 

if (asStringArray != null) 
    MessageBox.Show(string.Join("\n", asStringArray)); 

我真的不明白你爲什麼要以這種方式使用對象的數組,但我想有一些背景,你還沒有告訴我們。

0

excelfileNames是字符串的數組,因此當您分配給oVariableName [2] 時,應該爲其指定一個特定的值,而不是分配整個對象。

類似下面的代碼。

string [] excelFilesNames = new string[]{ "One","Two"}; 
    Object[] oVariableName = new object[3]; 
    oVariableName[2] = excelFilesNames[1];  
    MessageBox.Show(oVariableName[2].ToString()); 
+0

但我的需要是分配整個對象的值而不是一個特定的值。好吧,我得到了我的答案,謝謝你寶貴的時間。 –

相關問題