2015-05-04 88 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

但我的需要是分配整个对象的值而不是一个特定的值。好吧,我得到了我的答案,谢谢你宝贵的时间。 –

相关问题