C#:有没有办法使用反射来调整未知类型数组的大小?
我的用户向我传递某种类型的数组,例如 int[] 或 string[]。我可以通过 GetElementType 轻松查询元素的类型,并且可以找出通过 GetRank、GetLength 等传递给我的数组有多长。
数组在参数列表中传递,因此可视化代码如下:
public void Resizer(params object[] objs)
{
foreach (object o in objs)
Array.Resize(ref o, 3);
}
我想做的是与可用且有效的 Get 方法相反:我想调整传递给我的数组的大小,将长度设置为其他长度(如这个愚蠢示例中的 3)。
我这样做是因为在我的设置中,数组将包含从一组云计算服务器接收的数据,并且我们无法知道有多少服务器会提前响应,因此无法预先分配数组以具有正确的长度。事实上,理想情况下,我的用户传入一个长度为 0 的数组,而我传回一个长度为 n 的数组,这表示我从查询的服务器收到了 n 个回复。
我无法使用 Array.Resize(ref T, int) 执行此操作,因为我在编译时不知道 T。
有办法解决这个问题吗?
My users pass me an array of some type, say int[] or string[]. I can easily query the types of the elements via GetElementType, and I can find out how long the array was when it was passed to me via GetRank, GetLength, etc.
The arrays are passed in a params list, so visualize code like this:
public void Resizer(params object[] objs)
{
foreach (object o in objs)
Array.Resize(ref o, 3);
}
What I would like to do is the converse of the Get methods that are available and that do work: I want to resize the array that was passed to me, setting the length to some other length (like 3 in this silly example).
I'm doing this because in my setting the array will contain data received from a set of cloud computing servers and we can't know how many will respond in advance, hence can't preallocate the array to have the right length. Ideally, in fact, my user passes in an array of length 0, and I pass back an array of length n, signifying that I got n replies from the servers that were queries.
I can't do this with Array.Resize(ref T, int) because I don't know T at compile time.
Is there a way to pull this off?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这应该有效:
This should work:
为什么不直接创建一个您需要的任何类型的新数组以及您想要的大小呢?然后从要调整大小的数组中填充它,将不存在的值设置为某个默认值。
Why not just create a new array of whichever type you need that is the size that you want? Then populate it from the array you want to resize, setting non existent values to some default.
如果有人好奇,我最终将代码切换为使用 List
In case anyone is curious, I ended up switching my code to use List
我同意您应该使用 List(Of T) 的评论,但是如果您想将数组复制到相同类型的新数组中,您可以执行如下操作。
I agree with the comments that you should be using List(Of T), but if you want to copy your array into a new array of the same type, you could do something like the following.
我想我会改用列表,但这很遗憾;代码看起来会比较混乱,而且由于我的用户基本上处于第一学期本科生的水平,每一件小事都会让他们的生活变得不那么美好。但我怀疑你们也没有找到办法做到这一点。那好吧....
I guess I'll just switch to using Lists, but this is a shame; the code will be quite a bit messier looking and since my users are basically at the level of first-semester ugrads, each little thing will make their lives less good. But I'm suspecting that you folks don't see a way to do this either. Oh well....