在Visual Studio中使用带有图片框的标签
我正在练习C#编程,我正在学习一个我在网上找到的教程。我对Visual Studio女士感兴趣,并且目前正在进行自我教育。我已经从教程中完成了自己的编辑,但尽可能接近教程。一切似乎都很好,除了代码中有一部分我不知道我做了什么或研究。在教程中,它使我创建了我认为30个图片盒。每个图片框都被标记为块名或砖块的字名,或者您选择。我认为这是为了让所有图片框一次而不是一次一个地执行if/else语句更容易。我明白如果说“如果picturebox有标签”砖块“然后做XYZ,那么花费的时间会更少。” 无论如何,我将代码跟在T上,但是visualbasic说的是在Visual Studio中使用带有图片框的标签
“可能的意外引用comprarison;得到一个值比较,投左侧键入“串”
这里是代码的一部分,这给我这个
foreach (Control x in this.Controls)
{
if (x is PictureBox && x.Tag == "blockies")
{
if (pBall.Bounds.IntersectsWith(x.Bounds))
{
this.Controls.Remove(x);
pBally = -pBally;
score++;
}
}
}
它有一个绿色的波浪线从x.Tag到blockies” 。 感谢所有帮助 PS Windows窗体
这是因为Tag
不是一个字符串你需要做的,而不是x.Tag.ToString() == "blockies"
:
foreach (Control x in this.Controls)
{
if (x is PictureBox && x.Tag != null && x.Tag.ToString() == "blockies")
{
if (pBall.Bounds.IntersectsWith(x.Bounds))
{
this.Controls.Remove(x);
pBally = -pBally;
score++;
}
}
}
如果我这样做,我得到System.NullReferenceException:'对象引用未设置为对象的实例。' System.Windows.Forms.Control.Tag.get返回null。 – Razgr1z
@ Razgr1z在调用'ToString()'之前检查'x.Tag!= null'。发生这种情况时,您的标签为空。我编辑了我的答案来反映这个 –
如果您打开Control.Tag,您将看到它的定义。
public object Tag { get; set; }
您试图将对象与字符串进行比较,因此会显示此错误消息。
你应该做的是:
if (x is PictureBox && x.Tag.ToString() == "blockies")
还有一点你应该尽量避免箭头代码结构,这是真的很难阅读:
foreach (Control x in this.Controls)
{
if (!(x is PictureBox))
continue;
//this is needed if you want to use some specific property of the PictureBox.
PictureBox ctl = (PictureBox)x;
if(ctl.Tag.ToString() != "blockies")
continue;
if (!pBall.Bounds.IntersectsWith(ctl.Bounds))
continue;
//Also this line will create you a problem, because you will change the Control collection
//when you try to enumerate it. This should throw you an exception. Better make the control not visible.
//this.Controls.Remove(x);
x.Visible = false;
pBally = -pBally;
score++;
}
在这种情况下,你有更好的可读性代码。
你能解释一下为什么你低估了我,谢谢。 – mybirthname
不是我的倒计时,但你的三重'继续'可能不是每个人的口味。 – TaW
我发现使用Linq更具可读性。
修复您的问题进行比较警告,而在它枚举从集合中移除元素的问题:
foreach(var pb in this.Controls
.OfType<PictureBox>()
.Where(x => (string)x.Tag == "blockies")
.Where(x => pBall.Bounds.IntersectsWith(x.Bounds))
.ToList())
{
this.Controls.Remove(pb);
}
'但VisualBasic中被saying'这里是VB代码? –
这几乎是说上面引号。 – Razgr1z
我看到它,但没有任何与VB相关的东西。它是C# –