簡體   English   中英

用C#指示生成int數組?

[英]Pointers in C# to make int array?

以下C ++程序按預期編譯和運行:

#include <stdio.h>

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#中,默認情況下,對象表現為引用。 也就是說,您不必指定指針引用(&)和解除引用(*)語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM