gpt4 book ai didi

c# - 字符串枚举值已修改

转载 作者:行者123 更新时间:2023-11-30 15:12:20 26 4
gpt4 key购买 nike

我对 string 有一个疑问。 我们如何访问字符串的内存?

String是引用类型还是值类型?

1)如果是引用类型则执行如下代码

    List<String> strLst = new List<string>() { "abc","def","12"};
strLst.ForEach(delegate(string s)
{
if (s == "12")
{
s = "wser";
// I doubted whether = operator is overloaded in string class
//StringBuilder sb = new StringBuilder(s);
//s = sb.Append("eiru").ToString();
s = String.Concat(s, "sdf");
}
});

看到字符串的值没有改变。我的问题是为什么字符串值没有改变?如果是引用类型,则应更改字符串值。

class emp
{
public string id;
}


List<emp> e = new List<emp>() { new emp() { id = "sdf" }, new emp() { id = "1" }, new emp() { id = "2" } };

e.ForEach(delegate(emp em)
{
if (em.id == "1")
em.id = "fghe";
});

这里的值被改变了,因为emp是引用类型

2) 如果string是值类型

public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>,     IEnumerable<char>, IEnumerable, IEquatable<string>

那为什么他们提到字符串是一个类?

最佳答案

这是因为这部分而发生的:

s = "wser";

这完全等同于:

s = new String ("wser");

当你写这个的时候,一个新对象被实例化,它的引用被存储在 s 中。因此,先前的引用在函数范围内完全丢失,并且在范围外没有注意到任何变化。

因此,要注意在另一个范围内更改的引用类型的更改,您不能创建新实例并将其分配给变量名,您必须修改原始引用本身(这不是可能用于 Java 中的字符串对象 - 字符串是不可变的)。

关于c# - 字符串枚举值已修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1388403/

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