C# “增量”;属性信息设置值“;

C# “增量”;属性信息设置值“;,c#,propertyinfo,C#,Propertyinfo,这是我的代码: Enemy ble = new Enemy(); PropertyInfo prop = ble.GetType().GetProperty("x"); prop.SetValue(ble,20, null); Console.WriteLine(prop.GetValue(ble)); class Enemy { public int x { get; set; } = 20; } 正如你所看到的,我有

这是我的代码:

        Enemy ble = new Enemy();
        PropertyInfo prop = ble.GetType().GetProperty("x");
        prop.SetValue(ble,20, null);
        Console.WriteLine(prop.GetValue(ble));

class Enemy
{
    public int x { get; set; } = 20;
}

正如你所看到的,我有一个敌方类,我已经找到了如何找到属性“x”并将其值更改为设置值,在我的示例20中,但我的问题是,如何将其值增加或减少2,例如?

你已经使用了
GetValue()
SetValue()
,获取其值,并将其相加,然后再次设置新值:

prop.SetValue(ble,(int)prop.GetValue(ble) + 2, null);

你确定你需要反射吗?是的,我想我需要,我想在开始时用未知类型的动态创建的对象做一个小游戏,因为程序不知道动态对象的所有方法、属性等,我必须使用反射。首先获取值,然后将其递增2,并将其设置为新值是的,我已经尝试过了,但我得到的“运算符”+“不能应用于“object”和“int”类型的操作数。哦,对了,抱歉,没有看到。谢谢,就这样!