首页 > 解决方案 > 不安全关键字仅检查参数?

问题描述

我是 C# 新手,仍在努力理解 unsafe 的使用。假设我们有以下代码:

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方法不是还在处理方法体中的指针类型吗?并不意味着只检查参数以查看它是否是指针类型?那会有点愚蠢。

标签: c#.net

解决方案


推荐阅读