vb.net 在 VB 的 With 语句中有多个对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13446068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Have multiple objects in a With statement in VB?
提问by DemCodeLines
I have a lot of labels in VB that I use in Withstatement to set their properties.
我在 VB 中有很多标签,我在With语句中使用它们来设置它们的属性。
ProblemIs there any way I can do something like the following:
问题有什么办法可以做如下的事情:
With lblA, lblB, lblC
.fontColor = color.Red
End With
Is this possible, or do I have to manually do a Withstatement for each of them?
这是可能的,还是我必须手动With为每个人做一个声明?
回答by pinkfloydx33
I would keep those types of items in a list and then apply a for each loop on them, assuming they are all of the same type (or at least base type). Assuming you are using controls of type labelthis would be a solution. Note that I've modified .fontColorto .ForeColorso that this example works with the Label class:
我会将这些类型的项目保留在一个列表中,然后对它们应用 for 每个循环,假设它们都是相同的类型(或至少是基本类型)。假设您正在使用类型的控件,label这将是一个解决方案。请注意,我已修改.fontColor为.ForeColor使此示例适用于 Label 类:
Dim lblList as new List(of Label) ({lblA, lblB, lblC})
lblList.ForEach(sub(x) x.Fore Color = color.red)
Since you've posted your solution, you could still do the following to avoid the iteration loop over the array you made (which is why I do this as a list) not having to take into account the array size or anything:
由于您已经发布了您的解决方案,您仍然可以执行以下操作以避免在您制作的数组上进行迭代循环(这就是我将其作为列表执行的原因)而不必考虑数组大小或任何内容:
lblList.ForEach(Sub(x)
With x
.BackColor = Color.Black
.Dock = DockStyle.Top
.TextAlign = ContentAlignment.MiddleCenter
End With
End Sub)
回答by Neolisk
There is a shorter and more readable version of your solution:
您的解决方案有一个更短、更易读的版本:
For Each lbl As Label In {lblA, lblB, lblC}
With lbl
'...
End With
Next
回答by DemCodeLines
Here is the way I ended up doing it:
这是我最终这样做的方式:
Dim arrayMe As Label() = {lblA, lblB, lblC}
For count = 0 To arrayMe.Length - 1 Step 1
With arrayMe(count)
.BackColor = Color.Black
.Dock = DockStyle.Top
.TextAlign = ContentAlignment.MiddleCenter
End With
Next
There are other ways to do it, but I found this to be useful.
还有其他方法可以做到这一点,但我发现这很有用。

