在c#中的任意起始索引上初始化数组

jua*_*uan 6 c# arrays interop initialization ms-office

是否可以在c#中初始化一个数组,例如,subindex 1?

我正在使用Office互操作,并且每个属性都是一个从1开始的对象数组(我假设它最初是在VB.NET中编写的),你不能修改它,你必须设置整个数组才能接受它变化.

作为一种解决方法,我正在克隆原始数组,修改那个数组,并在完成后将其设置为一个整体.

但是,我想知道是否有可能创建一个新的非零基数组

小智 18

您可以按要求查看下面的代码.

// Construct an array containing ints that has a length of 10 and a lower bound of 1
Array lowerBoundArray = Array.CreateInstance(typeof(int), new int[1] { 10 }, new int[1] { 1 });

// insert 1 into position 1
lowerBoundArray.SetValue(1, 1);

//insert 2 into position 2
lowerBoundArray.SetValue(2, 2);

// IndexOutOfRangeException the lower bound of the array 
// is 1 and we are attempting to write into 0
lowerBoundArray.SetValue(1, 0);
Run Code Online (Sandbox Code Playgroud)

  • +1:一段有用的代码值得一千个关于*代码的不可读的散文链接. (6认同)