如题

解决方案 »

  1.   


    unsafe public static void usePoint()
        {
            int *p1,p2;
        }
      

  2.   

    //不安全代码只会在使用 /unsafe 编译的情况下出现
      

  3.   

    1. unsafe在C#程序中的使用场合:1)实时应用,采用指针来提高性能;2)引用非.net DLL提供的如C++编写的外部函数,需要指针来传递该函数;3)调试,用以检测程序在运行过程中的内存使用状况。2. 使用unsafe的利弊好处是:性能和灵活性提高;可以调用其他dll的函数,提高了兼容性;可以得到内存地址;带来麻烦是:非法修改了某些变量;内存泄漏。3. unsafe与unmanaged的区别managed code是在CLR监管下运行的程序。以下任务由CLR来执行:管理对象内存,类型安全检测和冗余处理。从另一方面来说,unmanaged code也就是能由程序员直接进行内存操作的程序。而unsafe是介于managed和unmanaged之间的桥梁,它使得managed code也能使用指针来控制和操作内存。4. unsafe的使用unsafe可以用来修饰类、类的成员函数、类的全局变量,但不能用来修饰类成员函数内的局部变量。编译带有unsafe代码的程序也要在“configuration properties>build” 中把允许unsafe代码设为真。但是在managed code中使用unsafe时也要注意,正因为CLR可以操作内存对象,假如你写了一下代码:      public unsafe void add(int *p)
          {
              *p=*p+4;
          }p的地址值可能会在运行过程中被CLR所修改,这通常可采用fixed来处理,使指针所指向的地址不能被改变。如下:      fixed(int *p=& value)
            {
                add(p);
            }
      

  4.   

    若要编译不安全代码,必须指定 /unsafe 编译器选项。无法通过公共语言运行库验证不安全代码。
    // cs_unsafe_keyword.cs
    // compile with: /unsafe
    using System;
    class UnsafeTest
    {
       // Unsafe method: takes pointer to int:
       unsafe static void SquarePtrParam(int* p)
       {
          *p *= *p;
       }   unsafe static void Main()
       {
          int i = 5;
          // Unsafe method: uses address-of operator (&):
          SquarePtrParam(&i);
          Console.WriteLine(i);
       }
    }
     
      

  5.   

    谢谢各位了
    解决了:解决方法如下
    <compiler language="c#;cs;csharp" extension=".cs" compilerOptions="/unsafe"type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /></compilers>你在中间加上一个属性即可  compilerOptions="/unsafe"