用C#指示生成int数组?

以下C ++程序按预期编译和运行:

#include  int main(int argc, char* argv[]) { int* test = new int[10]; for (int i = 0; i < 10; i++) test[i] = i * 10; printf("%d \n", test[5]); // 50 printf("%d \n", 5[test]); // 50 return getchar(); } 

我能为这个问题做出的最接近的C#简单示例是:

 using System; class Program { unsafe static int Main(string[] args) { // error CS0029: Cannot implicitly convert type 'int[]' to 'int*' int* test = new int[10]; for (int i = 0; i < 10; i++) test[i] = i * 10; Console.WriteLine(test[5]); // 50 Console.WriteLine(5[test]); // Error return (int)Console.ReadKey().Key; } } 

那么如何制作指针呢?

C#不是C ++ – 不要指望在C#中使用相同的东西工作。 它是一种不同的语言,在语法上有一些灵感。

在C ++中,数组访问是指针操作的简写。 这就是为什么以下是相同的:

 test[5] *(test+5) *(5+test) 5[test] 

但是,在C#中并非如此。 5[test]无效C#,因为System.Int32上没有索引器属性。

在C#中,你很少想要处理指针。 你最好直接将它作为一个int数组处理:

 int[] test = new int[10]; 

如果您确实想要出于某种原因处理指针数学,则需要标记您的方法不安全 ,并将其置于固定的上下文中 。 这在C#中并不典型,而且实际上可能完全没有必要。

如果你真的想要做这个工作,那么你在C#中最接近的将是:

 using System; class Program { unsafe static int Main(string[] args) { fixed (int* test = new int[10]) { for (int i = 0; i < 10; i++) test[i] = i * 10; Console.WriteLine(test[5]); // 50 Console.WriteLine(*(5+test)); // Works with this syntax } return (int)Console.ReadKey().Key; } } 

(再次,这真是奇怪的C# - 不是我推荐的......)

您需要使用fixed关键字fixed数组,以便GC不会移动它:

 fixed (int* test = new int[10]) { // ... } 

但是,C#中的不安全代码不是规则的例外。 我试着将你的C代码翻译成非不安全的C#代码。

你需要学习C#语言。 尽管与C / C ++存在语法上的相似之处,但它与Java一样,具有非常不同的方法。

在C#中,默认情况下,对象表现为引用。 也就是说,您不必指定指针引用(&)和解除引用(*)语法。