Added reflection usage in getSelectedNodeValue method

This commit is contained in:
abazov73 2023-09-21 22:56:56 +04:00
parent 1d0c82bfb4
commit 37fe5deca9
3 changed files with 37 additions and 5 deletions

View File

@ -113,7 +113,7 @@ namespace AbazovAppView
private void buttonGetValue_Click(object sender, EventArgs e)
{
Worker? worker = abazovTreeView.getSelecetedNodeValue();
Worker? worker = abazovTreeView.getSelecetedNodeValue<Worker>();
if (worker == null) return;
MessageBox.Show(worker.department + ", номер группы: " + worker.groupNumber + ", " + worker.name);
}

View File

@ -7,7 +7,6 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AbazovAppView;
namespace AbazovViewComponents.Components
{
@ -32,10 +31,43 @@ namespace AbazovViewComponents.Components
}
}
public Worker? getSelecetedNodeValue()
public T? getSelecetedNodeValue<T>()
{
if (treeView.SelectedNode == null || treeView.SelectedNode.Nodes.Count > 0) return null;
return new Worker(treeView.SelectedNode.Parent.Parent.Text, Convert.ToInt32(treeView.SelectedNode.Parent.Text), treeView.SelectedNode.Text);
if (treeView.SelectedNode == null || treeView.SelectedNode.Nodes.Count > 0) return default(T);
List<object> values = new List<object>();
List<string> fieldNames = new List<string>();
TreeNode? node = treeView.SelectedNode;
var type = typeof(T);
var fields = type.GetFields();
List<Type> types = new List<Type>();
while (node != null)
{
var field = fields.FirstOrDefault(x => x.Name == node.Name);
if (field != null)
{
Type typeOfField = field.FieldType;
types.Add(typeOfField);
values.Add(Convert.ChangeType(node.Text, typeOfField));
fieldNames.Add(field.Name);
}
node = node.Parent;
}
var constructor = type.GetConstructor(types.ToArray());
if (constructor == null) return default(T);
var parameters = constructor.GetParameters();
List<object> valuesForInvoking = new List<object>();
foreach (var param in parameters)
{
int index = fieldNames.IndexOf(param.Name);
valuesForInvoking.Add(values[index]);
}
return (T) constructor.Invoke(valuesForInvoking.ToArray());
}
public void setHierarchy(List<(string, bool)> fields)