【问题标题】:Setting value of generic property using reflection [duplicate]使用反射设置通用属性的值
【发布时间】:2020-05-18 02:26:04
【问题描述】:

我希望以动态方式设置 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;
        }
    }

【问题讨论】:

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

标签: c# reflection


【解决方案1】:

如果任意T你可以尝试Reflection一次:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多