为什么先前处理的子对象的父对象不会失败?
可能是令人尴尬的问题,但显然我缺少一些我想/需要知道的东西。
我希望以下代码创建一个新的表格行,其中包含稍后渲染的新单元格。这就是它的作用......正如您所期望的那样。
using (TableRow tr = new TableRow())
{
using (TableCell td = new TableCell())
{
td.Text = "Column A";
tr.Cells.Add(td);
}
using (TableCell td = new TableCell())
{
td.Text = "Column B";
tr.Cells.Add(td);
}
tbl.Rows.Add(tr);
}
但是……但是在 using 语句中创建的 TD 一旦超出“using”范围,是否就会失效?该行引用的 TD 对象现在是否无效,并且该行在尝试使用它们时不应该失败吗?当 TR 由“tbl”对象渲染时,情况也是如此。
我不明白处置吗?
是我不懂使用吗?
TableRow.Cells.Add() 实际上是在进行深层复制而不仅仅是 ref ptr 复制吗?
TableCell 废弃后还能用吗?
什么给?
Potentially embarrassing question, but there is obviously something I'm missing that I want/need to know.
I expect the following code to create a new table row with new cells to be rendered later. And that's what it does ... as you would expect.
using (TableRow tr = new TableRow())
{
using (TableCell td = new TableCell())
{
td.Text = "Column A";
tr.Cells.Add(td);
}
using (TableCell td = new TableCell())
{
td.Text = "Column B";
tr.Cells.Add(td);
}
tbl.Rows.Add(tr);
}
But .... but aren't the TDs created in the using statements invalidated once they go out of the 'using' scope? Wouldn't the TD objects referenced by the row now be invalid and shouldn't the row fail when it attempts to use them? The same could be said for the TR when it's rendered by the 'tbl' object.
Do I not understand dispose?
Do I not understand using?
Is TableRow.Cells.Add() actually doing a deep copy not just a ref ptr copy?
Can the TableCell actually be used after it's disposed?
What gives?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所有“using”块所做的就是确保在块末尾调用对象的“Dispose”方法。对象在被释放后仍然可以被使用和访问,但是由它们的“Dispose”方法的实现来知道如果这样做是否会发生任何不好的事情。
在这种情况下,它看起来不像 TableRow & 上的“Dispose”方法。 TableCell 会执行任何阻止将来使用它们的操作。这就是为什么你没有任何问题。
由于您确实希望将来使用这些对象,因此您根本不应该将它们放在“使用”块中。父页面对象应在页面生命周期结束时释放控件。
编辑:
我制作了一个测试服务器控件,并在其“Dispose”事件中放置了一个断点。下面是显示 .Net 调用 dispose 的堆栈跟踪。您可以使用 Reflector 更详细地查看代码。
All the "using" block does is ensure that the object's "Dispose" method is called at the end of the block. Objects can still be used accessed after they are disposed, but it's up to their implementation of the "Dispose" method to know if anything bad will happen if this is done.
In this case, it doesn't look like the "Dispose" method on TableRow & TableCell does anything that prevents them from being used in the future. That's why you don't have any problems.
Since you do want the objects to be used in the future, you shouldn't put them in "using" blocks at all. The parent page object should dispose of the controls at the end of the page lifecycle.
Edit:
I made a test server control and put a breakpoint in its "Dispose" event. Here's the stack trace that shows .Net calling dispose for you. You can use Reflector to look at the code in more detail.