属性通过反射增加值

本文关键字:增加值 反射 属性 | 更新日期: 2023-09-27 18:03:42

我需要知道如何使用反射为属性添加值例如,我有名称健康属性我想把值增加10

var prop = typeof (Character).GetProperty(actionParams.PropertyName);
var oldValue = (int)prop.GetValue(client.Character);
prop.SetValue(client.Character, Convert.ChangeType((oldValue + 10), prop.PropertyType));

但是我得到了转换错误

系统。InvalidCastException:指定的类型转换无效。

属性通过反射增加值

很可能您的名称为Health的属性不是int类型,因此强制转换(int)prop.GetValue(client.Character);失败