gpt4 book ai didi

c# - 没有 "Unassigned Local Variable"错误?

转载 作者:太空狗 更新时间:2023-10-29 22:34:13 27 4
gpt4 key购买 nike

为什么获取变量的地址可以消除“使用未分配的局部变量”错误?

(为什么一开始不初始化就可以取到地址?)

static unsafe void Main()
{
int x;
int* p = &x; //No error?!
x += 2; //No error?!
}

最佳答案

C# 语言规范,第 18.5.4 节:

The & operator does not require its argument to be definitely assigned, but following an & operation, the variable to which the operator is applied is considered definitely assigned in the execution path in which the operation occurs. It is the responsibility of the programmer to ensure that correct initialization of the variable actually does take place in this situation.
...
The rules of definite assignment for the & operator exist such that redundant initialization of local variables can be avoided. For example, many external APIs take a pointer to a structure which is filled in by the API. Calls to such APIs typically pass the address of a local struct variable, and without the rule, redundant initialization of the struct variable would be required.

关于c# - 没有 "Unassigned Local Variable"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6054750/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com