不安全的关键字只能检查参数吗?

时间:2019-06-05 04:17:09

标签: c# .net

我是C#的新手,但仍在努力理解不安全的用法。假设我们有以下代码:

static void Main(string[] args)
{
   unsafe 
   {
      int myInt = 10;
      SquareIntPointer(&myInt );  //OK here, in unsafe context
   }
   int myInt2 = 5;
   SquareIntPointer(&myInt2);   // compile error, not in unsafe context
}

static unsafe void SquareIntPointer(int* myIntPointer)
{
   // Square the value just for a test.
   *myIntPointer *= *myIntPointer;
}

但是如果我将代码更改为:

static void Main(string[] args)
{
   int myInt2 = 5;
   SquareIntPointer();   // OK here, but why?
}

static unsafe void SquareIntPointer()
{
   int random = 10;
   int* myIntPointer = &random;
   *myIntPointer *= *myIntPointer;
}

所以我们这里没有任何编译错误,但是SquareIntPointer方法不是仍然在处理方法体中的指针类型吗?并不意味着仅检查参数以查看其是否为指针类型?那会有点愚蠢。

0 个答案:

没有答案