edit lab 1 and accept

This commit is contained in:
revengel66 2024-10-15 10:44:45 +04:00
parent 5489c642f0
commit 2a0c55f7b5

View File

@ -71,48 +71,45 @@ namespace ComponentsLibrary
}
// Публичный параметризованный метод для получения объекта из выбранной строки
public T? GetSelectedItem<T>() where T : new()
public T GetSelectedItem<T>() 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;
}
}
}