#vb.net #loops
#vb.net #циклы
Вопрос:
Мне было интересно, есть ли способ сжать мой код с помощью цикла, вот мой код: (Cell_1_Containes — это RichTextBox)
Cell_1_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation "MainCellsCell 1Containes.txt")
Cell_2_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation "MainCellsCell 2Containes.txt")
Cell_3_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation "MainCellsCell 3Containes.txt")
Cell_4_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation "MainCellsCell 4Containes.txt")
Cell_5_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation "MainCellsCell 5Containes.txt")
Cell_6_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation "MainCellsCell 6Containes.txt")
Cell_7_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation "MainCellsCell 7Containes.txt")
Cell_8_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation "MainCellsCell 8Containes.txt")
Cell_9_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation "MainCellsCell 9Containes.txt")
Cell_10_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation "MainCellsCell 10Containes.txt")
Комментарии:
1. Что вы уже пробовали? Отредактируйте свой вопрос, чтобы показать ваши усилия.
2. если вы поместите все свои объекты cell в структуру списка или массива, то вы можете выполнить цикл над ними, чтобы задать их текст (и использовать переменную counter для изменения номера папки внутри строки path)
3. Code Review — это то место, куда следует обратиться, если вы хотите провести обзор и / или ищете альтернативы вашему рабочему решению.
Ответ №1:
Dim cells() As Control = {Cell_1_Containes, Cell_2_Containes,Cell_3_Containes,Cell_4_Containes,Cell_5_Containes,Cell_6_Containes,Cell_7_Containes,Cell_8_Containes,Cell_9_Containes,Cell_10_Containes}
For i As Integer = 0 To 9
cells(i).Text = My.Computer.FileSystem.ReadAllText(Path.Combine(MyLocation, $"MainCellsCell {i 1}Containes.txt"))
Next
Комментарии:
1. ИМХО, существует более чем несколько способов сделать это, ваш подход работает, но в то же время ограничен. Если пользователь добавит больше элементов управления, все это, в свою очередь, придется переписать. Я бы проголосовал за вопрос TBH, поскольку мы помогаем с конкретными проблемами, а не с обзором кода.