从using语句内修改值类型是否未定义行为? [英] Is modifying a value type from within a using statement undefined behavior?

查看:106
本文介绍了从using语句内修改值类型是否未定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这实际上是

This one's really an offshoot of this question, but I think it deserves its own answer.

根据ECMA-334第15.13节(在using声明中,以下称为 resource-acquisition ):

According to section 15.13 of the ECMA-334 (on the using statement, below referred to as resource-acquisition):

在a中声明的局部变量 resource-acquisition 是只读的,并且应包含一个初始化程序.一种 如果编译时发生编译时错误 嵌入式语句尝试修改 这些局部变量(通过赋值 或++--运算符)或 将它们作为refout传递 参数.

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.

这似乎可以解释为什么下面的代码是非法的.

This seems to explain why the code below is illegal.

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#中是未定义的和/或非法的吗?如果合法,那么此代码与上面的规范摘录之间的关系是什么?如果它是非法,为什么会起作用?是否存在一些允许它的微妙漏洞,或者事实证明它的工作仅是靠运气(因此,人们永远都不应依赖这种看似无害的代码的功能)?

Is the above snippet undefined and/or illegal in C#? If it's legal, what is the relationship between this code and the excerpt from the spec above? If it's illegal, why does it work? Is there some subtle loophole that permits it, or is the fact that it works attributable only to mere luck (so that one shouldn't ever rely on the functionality of such seemingly harmless-looking code)?

推荐答案

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

I would read the standard in such a way that

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

被禁止-出于令人信服的理由. 为什么对结构Mutable不允许我打败.因为对于一个类来说,代码是合法的并且可以很好地编译...(我知道对象类型.)

is forbidden - with reason that seem obious. Why for the struct Mutable it is not allowed beats me. Because for a class the code is legal and compiles fine...(object type i know..)

我也看不出更改值类型的内容确实危害RA的原因.有人在解释吗?

Also I do not see a reason why changing the contents of the value type does endanger the RA. Someone care to explain?

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

Maybe someone doing the syntx checking just misread the standard ;-)

马里奥(Mario)

这篇关于从using语句内修改值类型是否未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆