【发布时间】: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