I have a data object that has many different List properties. I want to use a single AddObject command instead of creating a different command for each List, so came up with the following code.
Is there any downsides you can see to using this? I thought performance might be slow, but I honestly haven't seen a difference.
public MyViewModel()
{
_addCommand = new RelayCommand<IEnumerable>(AddGenericObject);
// Old code.... defines an Add command per list
// _addAddressCommand = new RelayCommand(() => AddObject<Address>(AddressList));
// _addPhoneCommand = new RelayCommand(() => AddObject<Phone>(PhoneList));
// ... etc
}
private void AddGenericObject(IEnumerable list)
{
// Find Add Method
var addMethod = this.GetType()
.GetMethod("AddObject", BindingFlags.NonPublic | BindingFlags.Instance);
// Created Generic Add Method
Type genericType = list.GetType().GetGenericArguments()[0];
var genericAddMethod = addMethod.MakeGenericMethod(genericType);
// Invoke Method
genericAddMethod.Invoke(this, new object[] { list });
}
private void AddObject<T>(EntityCollection<T> list)
where T : EntityObject, new()
{
var newItem = new T();
list.Add(newItem);
}
It is used in the XAML by something like this:
<Button Content="New Address"
Command="{Binding AddCommand}"
CommandParameter="{Binding AddressList}" />
<Button Content="New Phone"
Command="{Binding AddCommand}"
CommandParameter="{Binding PhoneList}" />
In one word - performance, but before you rid of the code benchmark it - it might be fast enough for your needs.
Performance is always the biggest factor when considering the use of reflection. In general, you should try to avoid using reflection if you can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With