samedi 1 février 2020

Setting value of generic property using reflection

unit.GetType().GetProperty(args.PropertyName).SetValue(unit, args.PropertyValue);

This GetProperty(args.PropertyName) returns a generic that I created. For this example let's say it's SyncVar<int>. SyncVar has a Value property which ends up being T (int in this case but could be some other base type).

args.PropertyValue is of type 'dynamic' and ends up being the int value I need to set SyncVar's 'Value' variable to in my example. How can I dynamically do this? How can I dynamically set this 'Value' property of the SyncVar without hardcoding the T part of the SyncVar in question?

The above code tries to change the SyncVar property itself not the underlying int 'Value' property (when it's SyncVar<int> for example).

Just to add more detail I could do the below but it would be hardcoding the <int> part which I don't want to do:

var prop = (SyncVar<int>)unit.GetType().GetProperty(args.PropertyName).GetValue(unit);
prop.Value = args.PropertyValue;




Aucun commentaire:

Enregistrer un commentaire