不能对 C# 中的变量使用关键字 'fixed'
Can't use keyword 'fixed' for a variable in C#
我用数组和字符串变量测试了关键字 fixed
,效果非常好,但我不能使用单个变量。
static void Main() {
int value = 12345;
unsafe {
fixed (int* pValue = &value) { // problem here
*pValue = 54321;
}
}
}
行 fixed (int* pValue = &value)
导致编译器错误。我不明白,因为变量 value
不在 unsafe
块中并且尚未固定。
为什么我不能对变量 value
使用 fixed
?
这是因为value
是局部变量,分配在栈上,所以已经固定了。错误消息中提到了这一点:
CS0213 You cannot use the fixed statement to take the address of an already fixed expression
如果需要value
的地址,不需要fixed
语句,直接获取即可:
int* pValue = &value;
我用数组和字符串变量测试了关键字 fixed
,效果非常好,但我不能使用单个变量。
static void Main() {
int value = 12345;
unsafe {
fixed (int* pValue = &value) { // problem here
*pValue = 54321;
}
}
}
行 fixed (int* pValue = &value)
导致编译器错误。我不明白,因为变量 value
不在 unsafe
块中并且尚未固定。
为什么我不能对变量 value
使用 fixed
?
这是因为value
是局部变量,分配在栈上,所以已经固定了。错误消息中提到了这一点:
CS0213 You cannot use the fixed statement to take the address of an already fixed expression
如果需要value
的地址,不需要fixed
语句,直接获取即可:
int* pValue = &value;