I have a class that has a bunch of properties of certain type , this type has 3 events and I want to subscribe to this events on my class constructor, but avoiding typing each property name 3 times, is this possible?
Something like iterate trough all the properties of this type and add the event handlers?
internal class myValues {
public myValues () {
// Want to avoid hardcoding all my Properties here, and loop trough them all
Test1.AnyChanged += OnMetricChanged;
Test1.ValueChanged += OnMetricValueChanged;
Test1.DeltaChanged += OnMetricDeltaChanged;
...
...
// I can go trough all of them, but not sure how to add the handlers here
var properties = typeof(myValues).GetProperties().Where(p => p.PropertyType == typeof(Metric));
foreach (var p in properties) {
Debug.WriteLine(p.Name );
}
}
public Metric Test1 { get; private set; }
public Metric Test2 { get; private set; }
public Metric Test3 { get; private set; }
public Metric Test4 { get; private set; }
}
>Solution :
You could apply method extraction to property subscription and then iterate over properties via reflection to subscribe each of them
var myValues = new myValues();
public class Metric
{
public event EventHandler AnyChanged;
public event EventHandler ValueChanged;
public event EventHandler DeltaChanged;
}
public class myValues
{
public myValues()
{
var properties = typeof(myValues).GetProperties().Where(p => p.PropertyType == typeof(Metric));
foreach (var p in properties)
{
var metric = (Metric)p.GetValue(this);
SubscribeMetric(metric);
Console.WriteLine($"Subscribed {p.Name}");
}
}
private void SubscribeMetric(Metric metric)
{
metric.AnyChanged += OnMetricChanged;
metric.ValueChanged += OnMetricValueChanged;
metric.DeltaChanged += OnMetricDeltaChanged;
}
private void OnMetricDeltaChanged(object? sender, EventArgs e)
{
}
private void OnMetricValueChanged(object? sender, EventArgs e)
{
}
private void OnMetricChanged(object? sender, EventArgs e)
{
}
public Metric Test1 { get; set; } = new();
public Metric Test2 { get; set; } = new();
public Metric Test3 { get; set; } = new();
public Metric Test4 { get; set; } = new();
}