Compare commits

..

No commits in common. "3a02a9e7f2d7db979c5724373d79fea96679061b" and "bdf15f37cdf6c00e915ae1f20aecd61dc0f809d8" have entirely different histories.

2 changed files with 56 additions and 65 deletions

View File

@ -16,12 +16,25 @@ namespace WinFormsLibrary1
{ {
InitializeComponent(); InitializeComponent();
} }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="container"></param>
public ComponentWithBigText(IContainer container) public ComponentWithBigText(IContainer container)
{ {
container.Add(this); container.Add(this);
InitializeComponent(); InitializeComponent();
} }
/// <summary>
/// Создать документ
/// </summary>
/// <param name="filename"></param>
/// <param name="title"></param>
/// <param name="rows"></param>
/// <exception cref="ArgumentNullException"></exception>
public void CreateDocument(string filepath, string title, string[] rows) public void CreateDocument(string filepath, string title, string[] rows)
{ {
if (string.IsNullOrEmpty(filepath)) if (string.IsNullOrEmpty(filepath))

View File

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Windows.Forms; using System.Windows.Forms;
@ -11,9 +10,9 @@ namespace WinFormsLibrary1
{ {
private string? _template; private string? _template;
private char? _startSymbol; private string _startSymbol;
private char? _endSymbol; private string _endSymbol;
public int SelectedIndex public int SelectedIndex
{ {
get get
@ -25,13 +24,11 @@ namespace WinFormsLibrary1
listBox.SelectedIndex = value; listBox.SelectedIndex = value;
} }
} }
public ListBoxUserControl() public ListBoxUserControl()
{ {
InitializeComponent(); InitializeComponent();
} }
public void SetParams(string template, string fromChar, string toChar)
public void SetParams(string template, char? fromChar, char? toChar)
{ {
_template = template; _template = template;
_startSymbol = fromChar; _startSymbol = fromChar;
@ -40,81 +37,62 @@ namespace WinFormsLibrary1
public T? GetObject<T>() where T : class, new() public T? GetObject<T>() where T : class, new()
{ {
if (listBox.SelectedIndex == -1 || string.IsNullOrEmpty(_template) || !_startSymbol.HasValue || !_endSymbol.HasValue) if (listBox.SelectedIndex == -1)
throw new ArgumentException("Не хватает данных");
var type = typeof(T);
var fields = type.GetFields();
var properties = type.GetProperties();
var members = fields.Cast<MemberInfo>().Concat(properties.Cast<MemberInfo>()).ToArray();
var curObject = new T();
string text = listBox.SelectedItem?.ToString() ?? "";
var words = Regex.Split(_template, $@"\{_startSymbol.Value}.*?\{_endSymbol.Value}");
int firstWordStart = text.IndexOf(words[0], 0);
if (firstWordStart == -1)
throw new Exception("Не найден элемент шаблона");
if (firstWordStart != 0)
{ {
string beginning = text[..firstWordStart]; return null;
FillMember(_template.Substring(1, firstWordStart - 2), curObject, beginning, members);
} }
int start = 0; string selectedString = listBox.SelectedItem.ToString()!;
T obj = new T();
for (int i = 0; i < words.Length - 1; i++) string pattern = $@"{Regex.Escape(_startSymbol)}(.*?){Regex.Escape(_endSymbol)}";
MatchCollection matches = Regex.Matches(_template, pattern);
string[] words = selectedString.Split(' ');
int wordIndex = 0;
foreach (Match match in matches)
{ {
start = text.IndexOf(words[i], start); string propertyName = match.Groups[1].Value;
if (start == -1) var property = obj.GetType().GetProperty(propertyName);
throw new Exception("Не найден элемент шаблона"); if (property != null && property.CanWrite)
start += words[i].Length; {
if (wordIndex < words.Length)
int nextWordIndex = text.IndexOf(words[i + 1], start); {
if (nextWordIndex == -1) string propertyValue = words[wordIndex];
throw new Exception("Не найден следующий элемент шаблона"); property.SetValue(obj, Convert.ChangeType(propertyValue, property.PropertyType));
wordIndex++;
string valueBetween = text[start..nextWordIndex]; }
}
string layoutPart = _template.Substring(_template.IndexOf(words[i]) + words[i].Length);
int startCharIndex = layoutPart.IndexOf(_startSymbol.Value);
int endCharIndex = layoutPart.IndexOf(_endSymbol.Value);
string memberName = layoutPart.Substring(startCharIndex + 1, endCharIndex - startCharIndex - 1);
FillMember(memberName, curObject, valueBetween, members);
start = nextWordIndex;
} }
return (T?)curObject; return obj;
} }
private void SetMemberValue(object obj, MemberInfo member, object value) public void AddObject<T>(T obj)
{ {
if (member is PropertyInfo property) if (obj == null)
{ {
property.SetValue(obj, value); throw new ArgumentNullException("Добавляемый объект не существует!");
} }
else if (member is FieldInfo field) if (string.IsNullOrEmpty(_template) || string.IsNullOrEmpty(_startSymbol) || string.IsNullOrEmpty(_endSymbol))
{ {
field.SetValue(obj, value); throw new Exception("Заполните макетную строку!");
}
if (!_template.Contains(_startSymbol) || !_template.Contains(_endSymbol))
{
throw new Exception("Макетная строка не содержит нужные элементы!");
} }
}
private void FillMember(string memberName, object curObject, string value, MemberInfo[]? members) string processedString = _template;
{ foreach (var property in obj.GetType().GetProperties())
var member = members?.FirstOrDefault(x => x.Name == memberName) {
?? throw new Exception("Ошибка с поиском элемента"); string placeholder = $"{_startSymbol}{property.Name}{_endSymbol}";
object convertedValue = Convert.ChangeType(value, GetMemberType(member)); processedString = processedString.Replace(placeholder, $"{_startSymbol}{property.GetValue(obj)}{_endSymbol}");
}
SetMemberValue(curObject, member, convertedValue); listBox.Items.Add(processedString);
}
private Type GetMemberType(MemberInfo member)
{
return member is PropertyInfo property ? property.PropertyType : ((FieldInfo)member).FieldType;
} }
} }
} }