From 2a0c55f7b54471db9ec76f72c27fc32394562003 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Tue, 15 Oct 2024 10:44:45 +0400 Subject: [PATCH] edit lab 1 and accept --- ComponentsLibrary/ListBoxValues.cs | 65 ++++++++++++++---------------- 1 file changed, 31 insertions(+), 34 deletions(-) diff --git a/ComponentsLibrary/ListBoxValues.cs b/ComponentsLibrary/ListBoxValues.cs index 8d4a90b..03b0e92 100644 --- a/ComponentsLibrary/ListBoxValues.cs +++ b/ComponentsLibrary/ListBoxValues.cs @@ -71,48 +71,45 @@ namespace ComponentsLibrary } // Публичный параметризованный метод для получения объекта из выбранной строки - public T? GetSelectedItem() where T : new() + public T GetSelectedItem() where T : new() { var selectedItem = listBox.SelectedItem; - if (selectedItem != null) - { - string selectedString = selectedItem.ToString(); // Строка из ListBox - T obj = new T(); + if (selectedItem == null) + { + throw new Exception(); + } + string selectedString = selectedItem.ToString(); + T obj = new T(); - PropertyInfo[] properties = typeof(T).GetProperties(); + PropertyInfo[] properties = typeof(T).GetProperties(); - string pattern = layoutString; + string pattern = layoutString; - for (int i = 0; i < properties.Length; i++) - { - PropertyInfo prop = properties[i]; - string propertyPattern = $"{startSymbol}{prop.Name}{endSymbol}"; - if (i == properties.Length - 1) - { - pattern = pattern.Replace(propertyPattern, "(.*)"); - } - else - { - pattern = pattern.Replace(propertyPattern, "(.*?)"); - } - } - Regex regex = new Regex(pattern); - Match match = regex.Match(selectedString); - - if (match.Success) - { - for (int i = 0; i < properties.Length; i++) - { - string value = match.Groups[i + 1].Value; - object convertedValue = Convert.ChangeType(value, properties[i].PropertyType); - properties[i].SetValue(obj, convertedValue); - } - return obj; + for (int i = 0; i < properties.Length; i++) + { + PropertyInfo prop = properties[i]; + string propertyPattern = $"{startSymbol}{prop.Name}{endSymbol}"; + if (i == properties.Length - 1) + { + pattern = pattern.Replace(propertyPattern, "(.*)"); + } + else + { + pattern = pattern.Replace(propertyPattern, "(.*?)"); } } - return default; - } + Regex regex = new Regex(pattern); + Match match = regex.Match(selectedString); + for (int i = 0; i < properties.Length; i++) + { + string value = match.Groups[i + 1].Value; + object convertedValue = Convert.ChangeType(value, properties[i].PropertyType); + properties[i].SetValue(obj, convertedValue); + } + return obj; + + } } }