使用switch case语句的问题

我的代码如下。 基本上,我正在读取excel文件并将其内容存储到对象数组中。 然后,我使用switch case语句来执行不同的操作。 检查下面的代码: –

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data; using System.Drawing; using System.ComponentModel; using Excel = Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Excel; namespace Excel1 { class Program { public static void Main(string[] args) //public void ExcelOps() { //string str; Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:/WebServiceTemplate.xlsx"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; int numSheets = xlWorkbook.Sheets.Count; // // Iterate through the sheets. They are indexed starting at 1. // for (int sheetNum = 1; sheetNum <=1; sheetNum++) { Worksheet sheet = (Worksheet)xlWorkbook.Sheets[sheetNum]; // // Take the used range of the sheet. Finally, get an object array of all // of the cells in the sheet (their values). // object[,] valueArray = (object[,])xlRange.get_Value(XlRangeValueDataType.xlRangeValueDefault); // // Do something with the data in the array with a custom method. // ProcessInput(valueArray); } } public static void ProcessInput(object[,] valueArray) { foreach (var value in valueArray) { switch ((string)value.ToString()) { case "ITemplate.GetAllTemplate": { //ITemplate.GetAllTemplate break; } case "ITask.GetTaskInstanceFromTemplate": { //ITask.GetTaskInstanceFromTemplate break; } case "CreateTask": { //CreateTask break; } case "UpdateDatabase": { //UpdateDatabase break; } case "GetTaskStatus": { //GetTaskStatus break; } case "VerifyValue": { //VerifyValue } break; } } } } } 

当我构建它时,我得到一个错误对象引用未设置为对象的实例。
错误出现在switch语句中

有人可以帮我弄这个吗?

valueArray是一个多维对象数组,根据您的参数定义。 switch不支持。

  1. 您不能也不会对值数组执行切换; switch对单个值进行操作。 您可以使用foreach来展平数组,迭代每个值,然后应用开关,但是……
  2. 如错误所示, object不能在switch语句中使用,只能键入错误消息中指示的对象。 如果每个值都是整数,则将值转换为switch的int。

更新确定,现在它们再次成为字符串。

例:

 foreach(var value in valueArray) { switch(value as string) { case "ITemplate.GetAllTemplate": break; case "ITask.GetTaskInstanceFromTemplate": break; case "CreateTask": break; case "UpdateDatabase": break; case "GetTaskStatus": break; case "VerifyValue": break; } } 

错误消息指的是switch后括号中变量的类型。 在你的情况下,这是一个数组,所以显然不是(如错误信息所示) bool,char,string,integral,enum或相应的可空类型

这是非常自我解释:你不能将switch语句与valueArray对象一起使用,因为它的类型( object[,] )。

Switch不支持数组。 它需要一个参数,而案例应该根据它来定义。

例如:

  int num=3; switch(num) //in case of integer type Case 1: Case 2: ... } char ch='a'; switch(ch) //in case of character type { Case 'a': Case 'b': Case '/': ... }