gpt4 book ai didi

C# 通过引用赋值

转载 作者:可可西里 更新时间:2023-11-01 07:51:35 24 4
gpt4 key购买 nike

是否可以通过引用赋值?我知道 ref 必须在方法中使用。

string A = "abc";
string B = A;
B = "abcd";
Console.WriteLine(A); // abc
Console.WriteLine(B); // abcd

我可以吃点东西吗

string A = "abc";
string B = (ref)A;
B = "abcd"; // A was assigned to B as reference, so changing B is the same as changing A
Console.WriteLine(A); // abcd
Console.WriteLine(B); // abcd

最佳答案

这就是它的工作原理。字符串是引用类型——您的变量 A 是对堆上字符串的引用(如指针),而您只是将指针的值(字符串的地址)复制到变量 B 中。

当您将“abcd”分配给 B 时,您的示例不会更改 A 的值,因为字符串在 .net 中被特殊处理。正如凯文指出的那样,它们是不可变的——但同样重要的是要注意它们具有值类型语义,即赋值总是导致引用指向新字符串,并且不会更改存储在中的现有字符串的值变量。

如果您使用(例如)汽车而不是字符串,并更改属性,您会看到这种情况:

public class Car {
public String Color { get; set; }
}

Car A = new Car { Color = "Red" };
Car B = A;
B.Color = "Blue";
Console.WriteLine(A.Color); // Prints "Blue"

// What you are doing with the strings in your example is the equivalent of:
Car C = A;
C = new Car { Color = "Black" };

可能值得注意的是,它不适用于值类型(整数、 double 、 float 、长整数、小数、 bool 值、结构等)。这些按值复制,除非它们被装箱为 Object

关于C# 通过引用赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9792776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com