使用指针和ref关键字引用值有什么区别

Wal*_*der 17 c# unsafe

我有以下代码:

class Program
{
    private unsafe static void SquarePtrParam(int* input)
    {
        *input *= *input;
    }

    private static void SquareRefParam(ref int input)
    {
        input *= input;
    }

    private unsafe static void Main()
    {
        int value = 10;
        SquarePtrParam(&value);
        Console.WriteLine(value);

        int value2 = 10;
        SquareRefParam(ref value2);
        Console.WriteLine(value2);

        //output 100, 100
        Console.ReadKey();
    }
}
Run Code Online (Sandbox Code Playgroud)

将指针和ref关键字作为参数传递给方法有什么区别?

Nat*_*nSr 20

ref关键字的作用就像一个指针,而是从变化到在存储器中的对象的实际位置绝缘.指针是内存中的特定位置.对于垃圾收集的对象,此指针可能会更改,但如果您使用该fixed语句来阻止它,则不会更改.

你应该改变这个:

SquarePtrParam(&value);
Run Code Online (Sandbox Code Playgroud)

对此:

fixed (int* pValue = &value)
{
    SquarePtrParam(pValue);
}
Run Code Online (Sandbox Code Playgroud)

确保指针继续指向int您期望的数据.

http://msdn.microsoft.com/en-us/library/f58wzh21.aspx