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; var selectedItem = listBox.SelectedItem;
if (selectedItem != null) if (selectedItem == null)
{
throw new Exception();
}
string selectedString = selectedItem.ToString();
T obj = new T();
PropertyInfo[] properties = typeof(T).GetProperties();
string pattern = layoutString;
for (int i = 0; i < properties.Length; i++)
{ {
string selectedString = selectedItem.ToString(); // Строка из ListBox PropertyInfo prop = properties[i];
T obj = new T(); string propertyPattern = $"{startSymbol}{prop.Name}{endSymbol}";
if (i == properties.Length - 1)
PropertyInfo[] properties = typeof(T).GetProperties(); {
pattern = pattern.Replace(propertyPattern, "(.*)");
string pattern = layoutString; }
else
{
for (int i = 0; i < properties.Length; i++) pattern = pattern.Replace(propertyPattern, "(.*?)");
{
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;
} }
} }
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;
}
} }
} }