C#,对通过属性 (get) 获得的值使用++ 运算符

标签 c# properties

在C#中我们定义一个属性如下:

// m_age is a private int in the class Employee
public int Age
{
    get {return m_age;}
    set {m_age = value;}
}

现在,当我这样做的时候

static void Main()
{
    Employee e = new Employee(age: 28); // Create new Employee
    System.Console.WriteLine("Age: {0}", e.Age); // Prints 28
    
    // Now increase age by 1
    ++e.Age;

    System.Console.WriteLine("Age: {0}", e.Age); // Prints 29
}

为什么

++e.Age;

工作?我做了一些搜索,找到了 Properties - by value or by reference?

这篇文章有一个答案:

Technically it's always by value, but you have to understand what is being passed. Since it's a reference type, you are passing a reference back (but by value).

Hope that makes sense. You always pass the result back by value, but if the type is a reference you are passing the reference back by value, which means you can change the object, but not which object it refers to.

(我确实对值类型和引用类型有很好的理解,因此我很困惑)。

现在,如果确实如此

e.Age

返回 m_age 的副本(int 是一种值类型),我们不会将增量++ 应用于副本吗?

或者...以下是真的吗?

++e.Age;

完全一样/被翻译成

e.Age = e.Age + 1

只有那个

++e.Age;

返回一个值(e.Age递增后的值)而

e.Age = e.Age + 1

是一个赋值并且不返回值(例如 C++ 会做的)。

最佳答案

除非重新定义,否则 ++ 运算符将再次获取、修改和设置值。

检查这一点的一个好方法是定义 get 和 set,然后在 Debug模式下执行。此行为也是 detailed in the C# specification对于递增和递减运算符。

关于C#,对通过属性 (get) 获得的值使用++ 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33641689/

相关文章:

c# - 如何将私有(private)成员行为定义为方法或属性? C#

C# 属性和 "tostring"方法

c# - EF Core 2.0 使用 where 条件时不加载相关实体

c# - 如何为 Visual Studio 智能感知评论类的属性?

c# - Entity Framework - 一对多关系的问题

c# - 在 LINQ 中解构包含 ValueTuple 的容器

java - apache-commons-config PropertiesConfiguration : comments after last property is lost

java - 如何在 JAR 文件之外读取或写入 .properties 文件

javascript - 如何使用 const 关键字将 Javascript 常量创建为对象的属性?

C#-WPF : testing strategies