Pointers in C# to make int array?

后端 未结 3 756
感情败类
感情败类 2021-01-12 02:20

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

#include 

int main(int argc, char* argv[])
{
    int* test = new int[10];

    for (         


        
3条回答
  •  执念已碎
    2021-01-12 03:05

    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.

    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]
    

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

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

    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.

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

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

提交回复
热议问题