[英]How to implement something like int*[] in C#?
In C/C++, the type of array element can be int*.在 C/C++ 中,数组元素的类型可以是 int*。 Can C# implement something like it? C# 可以实现类似的东西吗? For example:例如:
int main()
{
int x = 1;
int y = 2;
int* a1[2];
a1[0] = &x;
a1[1] = &y;
*a1[0] = 3;
*a1[1] = 4;
printf("%d\n", x);
printf("%d\n", y);
}
This is the closest you are going to get to this code这是您最接近此代码的地方
static class Program
{
unsafe static void Main(string[] args)
{
int x = 1;
int y = 2;
var a1 = stackalloc int*[2];
a1[0] = &x;
a1[1] = &y;
*a1[0] = 3;
*a1[1] = 4;
Console.WriteLine("{0}", x);
Console.WriteLine("{0}", y);
}
}
int* a1[2]; ... *a1[0] = 3; *a1[1] = 4;
This is more or less equal to the following C# code:这或多或少等于以下 C# 代码:
int[][] a1 = new int[2][];
...
a1[0][0] = 3;
a1[1][0] = 4;
int x = 1; int y = 2; ... a1[0] = &x; a1[1] = &y;
If you want to use "pure .NET code" (not unsafe
etc.), you might simulate a primitive variable using an array with a size of [1]
.如果您想使用“纯 .NET 代码”(不是unsafe
等),您可以使用大小为[1]
的数组模拟原始变量。 I often used that method when programming in Java (for example to simulate out
or ref
parameters that exist in C# but not in Java):在 Java 中编程时,我经常使用该方法(例如,模拟 C# 中存在但 Java 中不存在的out
或ref
参数):
int[] x = new int[] { 1 }; // instead of int x = 1;
int[] y = new int[] { 2 }; // instead of int y = 2;
...
a1[0] = x;
a1[1] = y;
If you do this, you have to replace all occurrences of x
by x[0]
, of course:如果你这样做,你必须用x[0]
替换所有出现的x
,当然:
Console.WriteLine("x = " + x[0]); // instead of Console.WriteLine("x = " + x);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.