设置数组的Length属性 [英] Set Array's Length property

查看:147
本文介绍了设置数组的Length属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过某种技术更改数组的Length属性?

Is it possible to change an array's Length property with some technique?

我需要将数组的前x个成员传递给方法.项目要求阻止我分配任何堆分配,因此我不能使用任何Array.Resize()或创建新数组.

I need to pass first x members of an array to a method. The project requirements prevent me from allocating any heap allocation so I can't use any Array.Resize() or create a new array.

我无法更改SetVertices代码,因为它属于另一个库.它需要V[].我无法将IList<V>V*传递给它.

Also I can't change the SetVertices code because it belongs to another library. It needs V[]. I can't pass IList<V> or V* to it.

public void BuildIt(V[] verts,int x){
    verts.Length = x; //Compile error
    mesh.SetVertices(verts);
}

当然,代码不会编译.我需要一些技巧,例如反射或扩展方法,将数组伪装成较小的而没有,实际上是在创建较小的数组.我希望SetVertices()方法认为该数组具有x个成员,即使它具有更多成员.

Of course the code won't compile. I need some technique like reflection or extension methods to disguise the array as smaller without actually creating an smaller array. I want SetVertices() method to think the array has x members even though it has more.

测试了以下方法,但它们不起作用:

Tested the following approaches and they don't work:

  • stackalloc不起作用,因为它无法创建(或无法获得)真实的数组.
  • 浏览单声道项目时,我发现数组的Length属性正在调用GetLenght()和GetRank()方法来确定长度.除了不好的做法外,我不能用扩展方法覆盖此方法,因为实例方法优先于扩展方法(或者是否有其他方法可以强制执行?).

接下来将尝试代码注入.

Gonna try code injection next.

试图将代码发送到Array.GetLength()Array.Length中.似乎没有一种简单,可靠,跨平台的干净方法可以在运行时更改现有方法主体.

Tried to emit code into Array.GetLength() and Array.Length. It seems there is no easy, reliable, cross platform and clean way to change an existing method body at runtime.

推荐答案

如果数组和x不变,并且它们的数量不大,那么您可以全局分配它们一次,而不是局部分配它们.因此,您将投入内存并获得性能.

If the arrays and x are not changing and their number is not to big, then you could allocate them once globally, not locally. So, you would invest memory and gain performance.

这篇关于设置数组的Length属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆