当一个代码块使用unsafe修饰符标记时,c#允许在函数中使用指针变量。
不安全代码或非托管代码是指使用了指针变量的代码块。
下面的实例说明了 c# 中使用了 unsafe 修饰符时指针的使用:
using system;
namespace unsafecodeapplication
{
class program
{
static unsafe void main(string[] args)
{
int var = 20;
int* p = &var;
console.writeline("data is: {0} ", var);
console.writeline("address is: {0}", (int)p);
console.readkey();
}
}
} 为了编译不安全代码,您必须切换到命令行编译器指定 /unsafe 命令行。
例如,为了编译包含不安全代码的名为 prog1.cs 的程序,需在命令行中输入命令:
csc /unsafe prog1.cs
如果您使用的是 visual studio ide,那么您需要在项目属性中启用不安全代码。
步骤如下:
- 通过双击资源管理器(solution explorer)中的属性(properties)节点,打开项目属性(project properties)。
- 点击 build 标签页。
- 选择选项"allow unsafe code"。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!