相关疑难解决方法(0)

如果我的struct实现了IDisposable,那么当在using语句中使用时它会被装箱吗?

如果我的struct实现了IDisposable,那么当在using语句中使用时它会被装箱吗?

谢谢

编辑:这个timedlock是一个结构并实现Idisposable. http://www.interact-sw.co.uk/iangblog/2004/04/26/yetmoretimedlocking

编辑2:看看IL似乎如果你的结构公开Dispose()为public,当你忘记调用Dispose()时,编译器会在结构的一个实例超出范围时调用Dispose(例如,你没有使用"使用"声明)?

c#

23
推荐指数
4
解决办法
5840
查看次数

是否在using语句未定义的行为中修改值类型?

这个问题真的是这个问题的一个分支,但我认为它应该得到自己的答案.

根据ECMA-334第15.13节(关于using声明,以下称为资源获取):

资源获取中声明的局部变量 是只读的,并且应包括初始化器.如果嵌入语句试图修改这些局部变量(通过赋值或发生编译时间错误++--操作员)或它们传递作为refout 参数.

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

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;
}
Run Code Online (Sandbox Code Playgroud)

但是这个怎么样?

using (var e = new Mutable())
{
    // This is doing exactly the same thing, but …
Run Code Online (Sandbox Code Playgroud)

c# struct specifications using mutable

11
推荐指数
1
解决办法
385
查看次数

结构类型的深层副本是否也在"使用......"块中处理?

假设我有一个实现IDisposible的结构类型,如果我使用下面的代码:

using (MyStruct ms = new MyStruct())
{
     InnerAction(ms);   //Notice "InnerAction" is "InnerAction(MyStruct ms)"
}
Run Code Online (Sandbox Code Playgroud)

当然我看到在使用块之后,ms被处理掉了.然而,"InnerAction"中的结构呢?它是否仍然存在,因为深层复制或它也处置?

如果它仍然存活(未处理),我必须使用"ref"作为"InnerAction"吗?

请给我你的证明:)

大家好.

c# struct idisposable using

6
推荐指数
1
解决办法
140
查看次数

标签 统计

c# ×3

struct ×2

using ×2

idisposable ×1

mutable ×1

specifications ×1