c# delete dynamically created objects
我想删除所有动态创建的对象[在这种情况下,标签和轨迹栏]
1 2 3 4 5 6 | foreach (Label Labels in Controls.OfType<Label>()) { if (Labels.Tag.ToString() !="non-disposal"){ Labels.Dispose(); } } |
我试过这个,但我得到一个错误提示"对象引用未设置为对象的实例。
"
谢谢你,
解决方案:
1 2 3 4 | foreach (Label label in Controls.OfType<Label>()){ if (label.Tag != null && label.Tag.ToString() =="dynamic") label.Dispose(); |
感谢lazyberezovsky
向所有动态控件添加一些
1 2 3 4 5 | foreach (Label label in Controls.OfType<Label>()) { if (label.Tag != null && label.Tag.ToString() =="dynamic") label.Dispose(); } |
看起来有些标签没有分配
您需要将它们从控件集合中删除。
1 2 3 4 5 6 7 8 9 10 11 | var toDelete = Controls.OfType<Label>() .Where(c => (c.Tag ??"").ToString() !="non-disposal") .ToList(); //need a list or array to avoid changing the collection as we remove from it foreach (var ctrl in toDelete) { Controls.Remove(ctrl); ctrl.Dispose(); } //if this is part of a long method, also clear the list right away // so the garbage collector can see them toDelete.Clear(); |