在 C# 中的任意起始索引上初始化数组
在 C# 中是否可以在子索引 1 等位置初始化数组?
我正在使用 Office 互操作,每个属性都是一个从 1 开始的对象数组(我假设它最初是在 VB.NET 中编程的),并且您无法修改它,您必须设置整个数组以使其接受变化。
作为一种解决方法,我克隆原始数组,修改该数组,并在完成后将其设置为一个整体。
但是,我想知道是否可以创建一个新的非零基数组
Is it possible in c# to initialize an array in, for example, subindex 1?
I'm working with Office interop, and every property is an object array that starts in 1 (I assume it was originally programed in VB.NET), and you cannot modify it, you have to set the entire array for it to accept the changes.
As a workaround I am cloning the original array, modifying that one, and setting it as a whole when I'm done.
But, I was wondering if it was possible to create a new non-zero based array
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
可以按照您的要求进行操作,请参阅下面的代码。
It is possible to do as you request see the code below.
您可以使用
Array.CreateInstance
。请参阅.NET 中的数组类型
You can use
Array.CreateInstance
.See Array Types in .NET
不简单。 但你当然可以编写自己的类。 它将有一个数组作为私有变量,用户会认为他的数组从 1 开始,但实际上它从 0 开始,并且您从他的所有数组访问中减去 1。
Not simply. But you can certainly write your own class. It would have an array as a private variable, and the user would think his array starts at 1, but really it starts at zero and you're subtracting 1 from all of his array accesses.
您可以编写自己的数组类
You can write your own array class
我不认为是否可以修改数组的起始索引。
我将使用泛型创建自己的数组并在内部处理它。
I don't think if it's possible to modify the starting index of arrays.
I would create my own array using generics and handle it inside.
只需将名为“offset”的 const int 保留为 1,并始终将其添加到代码中的下标中。
Just keep of const int named 'offset' with a value of one, and always add that to your subscripts in your code.
我认为您无法在 C# 中创建基于非零的数组,但您可以轻松地围绕内置数据结构编写自己的包装类。该包装类将保存您所需的数组类型的私有实例; 不允许重载 [] 索引运算符,但您可以向类添加索引器,使其表现得像可索引数组,请参阅 此处。 然后,您编写的索引函数可以向传入的所有索引添加(或减去)1。
然后您可以按如下方式使用您的对象,它会正常运行:
I don't think you can create non-zero based arrays in C#, but you could easily write a wrapper class of your own around the built in data structures.This wrapper class would hold a private instance of the array type you required; overloading the [] indexing operator is not allowed, but you can add an indexer to a class to make it behave like an indexable array, see here. The index function you write could then add (or subtract) 1, to all index's passed in.
You could then use your object as follows, and it would behave correctly:
在 VB6 中,您可以将数组更改为以 0 或 1 开头,因此我认为 VBScript 也可以执行相同的操作。 对于 C#,这是不可能的,但您可以简单地在第一个 [0] 中添加 NULL 值,并从 [1] 开始实际值。 当然,这有点危险……
In VB6 you could change the array to start with 0 or 1, so I think VBScript can do the same. For C#, it's not possible but you can simply add NULL value in the first [0] and start real value at [1]. Of course, this is a little dangerous...