下面是一个 Win32 控制台应用程序,演示了各种指针对数组的依赖性。例如,通过取消注释标记为“//uncomment ...”的行来更改原始数组(模型)中的值会导致输出发生更改。我的问题是如何在 C# 托管代码环境中获得或模仿这种行为(即不使用不安全和指针)?
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
float model[100];
for(int i = 0; i < 100; i++) { model[i] = i; }
// uncomment these to alter the results
//model[5] = 5000;
//model[20] = 20000;
//model[38] = 38000;
static const int componentCount = 5;
float* coefs = model; // coefs points to model[0]
float* mean = coefs + componentCount; // mean points to model[0 + componentCount] == model[5]
float* cov = mean + 3*componentCount; // cov points to model[0 + componentCount + 3*componentCount] == model[20]
int ci = 2;
float* c = cov + 9*ci; // c points to model[0 + componentCount + 3*componentCount + 9*ci] == model[38]
int i = 0;
cout <<"model : "<< model[i] << endl; // 0
cout <<"coefs : "<< coefs[i] << endl; // 0
cout <<"mean : "<< mean[i] << endl; // 5 (or 5000)
cout <<"cov : "<< cov[i] << endl; // 20 (or 20000)
cout <<"ci : "<< ci << endl; // 2
cout <<"c : "<< c[i] << endl; // 38 (or 38000)
cin.get(); }
最佳答案
您可以在没有不安全代码的情况下在 C# 中执行相同的操作:
struct ArrayPointer<T>
{
private T[] array;
private int offset;
public ArrayPointer(T[] array) : this(array, 0)
{
}
private ArrayPointer(T[] array, int offset)
{
Debug.Assert(array != null);
Debug.Assert(offset >= 0);
Debug.Assert(offset < array.Length);
this.array = array;
this.offset = offset;
}
public static ArrayPointer<T> operator+(ArrayPointer<T> p1, int p2)
{
return new ArrayPointer<T>(p1.array, p1.offset + p2);
}
等等。定义加法、减法、递增、递减、比较、索引、数组转换等运算符。然后你可以说:
int[] arr = whatever;
ArrayPointer<int> pointer = arr;
pointer+=2;
pointer--;
int x = pointer[3];
等等。
这种方法有很多不错的特性。例如,如果在 p1 和 p2 是指向不同数组内部的指针时比较 p1 > p2,则可以执行调试断言。这几乎总是 C 中的错误,但很难捕捉。
关于c# - C++ 到 C# : Pointers & Arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4298508/