什么价值将有我的对象的属性? [英] what value will have property of my object?

查看:149
本文介绍了什么价值将有我的对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜在我的对象我看来财产shouold是2,但这个代码后,仍然是1,为什么?

Hi in my opinion property of my object shouold be 2, but after this code, is still 1, why?

internal class Program
{
    private static void Main(string[] args)
    {
        MyClass value = new MyClass() { Property = 1 };

        value.Property = value.Property++;
        Console.WriteLine(value.Property);
        Console.ReadKey();
    }
}

internal class MyClass
{
    public int Property;
}

在我看来,这应该value.Property = value.Property ++;首先把珍惜是什么价值,这对象,为什么ID不起作用的增加财产?

in my opinion this should value.Property = value.Property++; first put to value what is in value and the increment property of this object, why id doesn't work?

推荐答案

这是什么确实是:


  1. 评估 value.Property 在右侧(结果1)并记住结果

  2. 增量 value.Property (现在是等于2)

  3. 分配想起结果 value.Property (它现在再次等于1!)

  1. Evaluate value.Property on the right hand side (result is 1) and remember the result
  2. Increment value.Property (now it's equal to 2)
  3. Assign the remembered result to value.Property (it's now again equal to 1!)

如果您更改属性与明确的getter和setter属性,并把二传里面的一些调试代码,你会看到它确实改变值1 - > 2 - > 1

If you change Property to a property with an explicit getter and setter and put some debugging code inside the setter, you will see that it does indeed change values 1 -> 2 -> 1.

如果您更改 value.Property ++ ++ value.Property ,前两个步骤将得到扭转,所以我们倒是有:

If you changed value.Property++ to ++value.Property, the first two steps would be reversed, so we 'd have:


  1. 增量 value.Property (现在是等于2)

  2. 评估 value.Property 在右侧(它仍然是2)

  3. 第2步的结果分配给 value.Property (它仍然是2)

  1. Increment value.Property (now it's equal to 2)
  2. Evaluate value.Property on the right hand side (it's still 2)
  3. Assign the result of step 2 to value.Property (it's still 2)

当然,这是不必要的复杂,甚至可以说,是错误的。如果你想增加属性,所有你需要做的是这样的:

Of course, this is unnecessarily complicated and one could even say, wrong. If you want to increment Property, all you have to do is this:

++value.Property;

这篇关于什么价值将有我的对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆