无法在C#中将关键字“固定"用于变量 [英] Can't use keyword 'fixed' for a variable in C#
问题描述
我用数组和字符串变量对关键字 fixed
进行了测试,效果很好,但是我不能使用单个变量.
I tested the keyword fixed
with array and string variables and worked really well but I can't use with a single variable.
static void Main() {
int value = 12345;
unsafe {
fixed (int* pValue = &value) { // problem here
*pValue = 54321;
}
}
}
固定的行(int * pValue =& value)
会导致编译器错误.我不明白,因为变量 value
不在 unsafe
块之外,并且尚未固定.
The line fixed (int* pValue = &value)
causes a complier error. I don't get it because the variable value
is out of the unsafe
block and it is not pinned yet.
为什么不能对变量 value
使用 fixed
?
Why can't I use fixed
for the variable value
?
推荐答案
这是因为 value
是在堆栈上分配的局部变量,因此它已经固定.错误消息中提到了这一点:
This is because value
is a local variable, allocated on the stack, so it's already fixed. This is mentioned in the error message:
CS0213您不能使用fixed语句获取已经固定的表达式的地址
CS0213 You cannot use the fixed statement to take the address of an already fixed expression
如果您需要 value
的地址,则不需要 fixed
语句,则可以直接获取它:
If you need the address of value
, you don't need the fixed
statement, you can get it directly:
int* pValue = &value;
这篇关于无法在C#中将关键字“固定"用于变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!