在C#中的指针,以int数组? [英] Pointers in C# to make int array?

查看:130
本文介绍了在C#中的指针,以int数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的C ++程序编译和运行正常:

The following C++ program compiles and runs as expected:

#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#简单的例子,我可以弥补这方面的问题是:

The closest C# simple example I could make for this question is:

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;
    }
}

那么,如何使指针?

So how do I make the pointer?

推荐答案

C#不是C ++ - 不要指望同样的事情在在C ++中工作C#的工作。这是一个不同的语言,在语法一些启发。

C# is not C++ - don't expect the same things to work in C# that worked in C++. It's a different language, with some inspiration in the syntax.

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

In C++, array access is a short hand for pointer manipulation. That's why the following are the same:

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

然而,这不是在C#真。 5 [测试] 不是有效的C#,由于对System.Int32没有索引器属性。

However, this is not true in C#. 5[test] is not valid C#, since there is no indexer property on System.Int32.

在C#中,你很少要处理的指针。你最好只把它当作一个int数组直接:

In C#, you very rarely want to deal with pointers. You're better off just treating it as an int array directly:

int[] test = new int[10];

如果你真的想要对付指针数学出于某种原因,你需要你的标志方法不安全,并把它变成一个固定的情况下。这不会是在C#典型的,实际上可能是一些完全不必要的。

If you really do want to deal with pointer math for some reason, you need to flag your method unsafe, and put it into an fixed context. This would not be typical in C#, and is really probably something completely unnecessary.

如果你真的想使这项工作,最接近你可以在C#做的是:

If you really want to make this work, the closest you can do in C# would be:

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# - 不是我建议......)

(Again, this is really weird C# - not something I'd recommend...)

这篇关于在C#中的指针,以int数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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