gpt4 book ai didi

c# - 从 using 语句中修改值类型是未定义的行为吗?

转载 作者:可可西里 更新时间:2023-11-01 08:45:45 25 4
gpt4 key购买 nike

这个真的是 this question 的一个分支,但我认为它应该得到自己的答案。

根据 ECMA-334 的第 15.13 节(关于 using 语句,以下称为 resource-acquisition):

Local variables declared in a resource-acquisition are read-only, and shall include an initializer. A compile-time error occurs if the embedded statement attempts to modify these local variables (via assignment or the ++ and -- operators) or pass them as ref or out parameters.

这似乎解释了为什么下面的代码是非法的。

struct Mutable : IDisposable
{
public int Field;
public void SetField(int value) { Field = value; }
public void Dispose() { }
}

using (var m = new Mutable())
{
// This results in a compiler error.
m.Field = 10;
}

但是这个呢?

using (var e = new Mutable())
{
// This is doing exactly the same thing, but it compiles and runs just fine.
e.SetField(10);
}

上述代码片段在 C# 中是否未定义和/或非法?如果合法,这段代码与上述规范的摘录之间有什么关系?如果它是非法的,那它为什么有效?是否有一些微妙的漏洞允许它,或者它的工作仅仅是运气的事实(所以人们不应该依赖这种看似无害的代码的功能)?

最佳答案

我会以这样的方式阅读标准

using( var m = new Mutable() )
{
m = new Mutable();
}

被禁止 - 原因似乎令人厌恶。为什么不允许 struct Mutable 击败我。因为对于一个类来说,代码是合法的并且编译得很好......(我知道的对象类型......)

我也看不出更改值类型的内容会危及 RA 的原因。有人愿意解释一下吗?

也许有人在做语法检查只是误读了标准;-)

马里奥

关于c# - 从 using 语句中修改值类型是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4662633/

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