C# 使用反射设置泛型属性的值

C# 使用反射设置泛型属性的值,c#,reflection,C#,Reflection,在动态方式中,我希望设置Unit类的SyncVar属性的.Value属性。下面的代码不会编译,我不想硬编码SynvVar,因为它可能是许多基本类型,,,等等 class SyncVar<T> { public T Value { get; set; } } class Unit { public SyncVar<int> Health { get; set; } = new SyncVar<int&g

在动态方式中,我希望设置Unit类的SyncVar属性的.Value属性。下面的代码不会编译,我不想硬编码
SynvVar
,因为它可能是许多基本类型
,等等

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;
        }
    }
classsyncvar
{
公共T值{get;set;}
}
班级单位
{
公共SyncVar运行状况{get;set;}=new SyncVar();
}
班级计划
{
静态void Main(字符串[]参数)
{
单位=新单位();
unit.Health.Value=100;
var prop=unit.GetType().GetProperty(“健康”).GetValue(单位);
//编译错误,因为prop对象不包含.Value
//我需要动态地找出这个泛型属性中使用了什么类型,这样我就可以转换到那个类型并设置它的值
属性值=50;
}
}
在任意
T
的情况下,您可以再次尝试反射:

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