在 for 循环中制作 var

Making var 's in a for-loop

这很难解释,但我会在我的代码中展示一个我想要的例子: 目前我是这样做的:

var something1 = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);
var something2 = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);
var something3 = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);

something1.Name = "sheet1";
something2.Name = "sheet2";
something3.Name = "sheet3";

我想在 for 循环中制作这些变量 这就是我认为应该是的:

for (int i=1;i<4;i++)
{
   var ("something" +i) = new Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet); // this (of course) doenst work
}

关于如何做到这一点有什么想法吗?

我试过了,但没用:

var something = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1 , XlSheetType.xlWorksheet)[4];

如果您确定需要多少实例,创建 class 个实例的数组或列表就可以满足您的需求。

如果您想要更复杂的东西,您还可以创建一个字典,在其中为每个 class 实例提供名称,这可以为您提供按名称访问的机制。

你可以使用字典

var somethigs = new Dictionary<int, xxx.ApplicationClass>();
for (var i = 1; i < 4; i++)
{
    somethigs[i] = new xxx.ApplicationClass();
}

//access them like this

somethigs[1].Name = "sheet1";
somethigs[2].Name = "sheet2";

或者使用这样的数组

var somethigs = new xxx.ApplicationClass[4];
for (var i = 0; i < 4; i++)
{
    somethigs[i] = new xxx.ApplicationClass();
}

somethigs[0].Name = "sheet1";
somethigs[1].Name = "sheet2";

请记住,数组具有从零开始的索引。

Dictionary<string, ApplicationClass> dictionary = new Dictionary<string, ApplicationClass>();
for(int i = 0; i < 4; i++) {
    dictionary.Add("something" + i, new xxx.ApplicationClass());
}

var myApplicationClass = dictionary["something1"];

你应该使用数组。在您的特定情况下,

var something = new xxx.ApplicationClass[4];
for (int i = 0; i < 3; i++)
{
    something[i] = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);
    something[i].Name = "sheet" + (i + 1).ToString();
}

您可能应该查找有关哪些数组及其工作原理的更多信息。例如参见 [​​=11=]