简体   繁体   English

包含另一个int变量的int变量是否会被视为引用类型?

[英]Would an int variable containing another int variable be considered a reference type?

I understand that value types hold values directly (int, bool, etc.), while reference types (such as classes) hold references to where the values are stored. 我知道值类型直接保存值(int,bool等),而引用类型(如类)保存对值存储位置的引用。 I haven't yet found an answer to this specific question in other posts regarding reference and value types. 我还没有在其他有关引用和值类型的帖子中找到此特定问题的答案。

int x = 10;
int y = x;

// Would y be considered a reference type?

I ask this because while "int x" is a value type, "y" doesn't hold a value directly, it "references" to "x" (a different location in memory). 我之所以这样问,是因为“ int x”是值类型,“ y”并不直接持有值,而是“引用”“ x”(内存中的另一个位置)。

Would y be considered a reference type? y被认为是引用类型?

No. 没有。

Reference type vs. value type is a property of the type itself , not any of the variables of that type. 引用类型与值类型是类型本身的属性,而不是该类型的任何变量。 Type int is a value type; 类型int是一个值类型; therefore, all variables of type int are variables of a value type. 因此,所有int类型的变量都是值类型的变量。

In your particular scenario, once y is assigned the value of x , it gets a copy of that value, not a reference to it. 在您的特定情况下,为y分配x的值后,它将获得该值的副本 ,而不是对其的引用。 The values of x and y could be assigned independently of each other. xy的值可以彼此独立分配。 If you subsequently change x , the value of y would remain unchanged: 如果随后更改x ,则y的值将保持不变:

int x = 10;
int y = x;
x = 5;
Console.WriteLine(y); // Prints 10

In contrast, variables of reference type "track" changes to the object that they reference: 相反,引用类型为“ track”的变量将更改为它们引用的对象:

StringBuilder x = new StringBuilder("Hello");
StringBuilder y = x;
x.Append(", world");
Console.WriteLine(y); // Prints "Hello, world"

I ask this because while "int x" is a value type, "y" doesn't hold a value directly, it "references" to "x" (a different location in memory). 我之所以这样问,是因为“ int x”是值类型,“ y”并不直接持有值,而是“引用”“ x”(内存中的另一个位置)。

y does not reference to x . y不引用x For value types, the assignment (via the = operator) means to copy the value from the variable on the right side to the variable on the left side. 对于类型,赋值(通过=运算符)意味着 从右侧的变量复制到左侧的变量。

For reference types, it means to copy the reference . 对于引用类型,这意味着复制引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM