使用反射设置通用属性的值

用户441521

以动态方式,我希望设置 Unit 类的 SyncVar 属性的 .Value 属性。下面将无法编译,我不想硬编码SynvVar<int>,因为它可能是一些基本类型<int><string><bool>,等。

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;
        }
    }
德米特里·比琴科

任意 情况下,T您可以再尝试一次反射

      prop.GetType().GetProperty("Value").SetValue(prop, 50);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章