为什么c不让using变量作为ref或out传递给函数
【腾讯云】亏本大甩卖,服务器4核16G 1年370元(带宽12M,系统盘120GB SSD盘,月流量2000GB)!!!!!!
云产品 配置 价格
服务器 1核2G,带宽5M,系统盘50GB SSD盘,月流量500GB 38元/年
MySQL 1核1G 19元/年
服务器 16核32G,带宽18M,系统盘250GB SSD盘,月流量5000GB 1197元/年
点我进入腾讯云,查看更多详情

Possible Duplicate:
Passing an IDisposable object by reference causes an error?

Why doesn't C# allow passing a variable from a using block to a function as ref or out?

This is my code:

using (Form s = new Form())
{
    doSomthing(ref s);
}

The function ends before the using block ends, why doesn't C# let me pass s as ref or out parameter?

#0

using variables are treated as readonly, as any reassignment is probably an error. Since ref allows reassignment, this would also be an issue. At the IL level, out is pretty-much identical to ref.

However, I doubt you need ref here; you are already passing a reference to the form, since it is a class. For reference-types, the main purpose of a ref would be to allow you to reassign the variable, and have the caller see the reassignment, i.e.

void doSomething(ref Form form)
{
    form = null; // the caller will see this change
}

it is not required if you are just talking to the form object:

void doSomething(Form form)
{
    form.Text = "abc"; // the caller will see this change even without ref
}

since it is the same form object.

#1

The var in a using() statement is considered read-only inside the block. See § 8.13:

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

But note that this only applies to variables declared as part of the using statement, the following is legal (just not a good idea):

var f2 = System.IO.File.OpenText("");
using (f2)
{
    f2 = null;
}

#2

One reason could be that doSomthing could make s refer to another Form instance than the one we have created. That could introduce a resource leak since the using block would then invoke Dispose on the Form instance that came from the method, and not the one created in the using block.

推荐文章

有关xCode中ViewController的常规信息

有关xCode中ViewController的常规信息

推荐文章

Excel模拟

Excel模拟

推荐文章

数据库连接通过。菲律宾比索

数据库连接通过。菲律宾比索

推荐文章

Rmpi从设备调用用户定义函数时出错

Rmpi从设备调用用户定义函数时出错

推荐文章

如何调用Firefox书签对话框?

如何调用Firefox书签对话框?

推荐文章

Mvp模式asp.net

Mvp模式asp.net

推荐文章

我们可以用java读取swf文件吗?

我们可以用java读取swf文件吗?

推荐文章

午夜为0时发生Datenum错误

午夜为0时发生Datenum错误

推荐文章

COM互操作,C,Visual Studio 2010->嵌入互操作类型

COM互操作,C,Visual Studio 2010->嵌入互操作类型

推荐文章

使用php将多个嵌套数组写入文件

使用php将多个嵌套数组写入文件

推荐文章

数据库未存储查询

数据库未存储查询

推荐文章

试一试之后应该总是接住吗?

试一试之后应该总是接住吗?

推荐文章

如何确定现有项目的部署目标iOS版本

如何确定现有项目的部署目标iOS版本

推荐文章

EF 4.1带连接的ExecuteStoreQuery

EF 4.1带连接的ExecuteStoreQuery

推荐文章

可以用PHP创建IPHONE应用程序吗?

可以用PHP创建IPHONE应用程序吗?

推荐文章

在stdafx.h内部声明时出错

在stdafx.h内部声明时出错