samedi 1 février 2020

Setting value of generic property using reflection [duplicate]

In a dynamic way, I'm looking to set the .Value property of the SyncVar property of the Unit class. The following won't compile and I don't want to hardcode SynvVar<int> because it could be a number of base types <int>, <string>, <bool>, etc.

class SyncVar<T>
    {
        public T Value { get; set; }
    }

    class Unit
    {
        public SyncVar<int> Health { get; set; } = new SyncVar<int>();
    }

    class Program
    {
        static void Main(string[] args)
        {
            Unit unit = new Unit();
            unit.Health.Value = 100;

            var prop = unit.GetType().GetProperty("Health").GetValue(unit);

            // compile error as prop object doesn't contain .Value
            // I need to dynamically figure out what type was used in this generic property so I can cast to that and set it's value
            prop.Value = 50;
        }
    }




Aucun commentaire:

Enregistrer un commentaire