如何通过引用将字符串传递到集合中?
似乎字符串是引用,但按值复制
List<string> data = new List<string>();
string s = "a";
data.Add(s); // copy by value??
s = "b";
Console.WriteLine(data[0]); // "a"
它也似乎类是按引用复制的引用
class boxstring { public string val; }
List<boxstring> data = new List<boxstring>();
boxstring s = new boxstring { val = "a" };
data.Add(s); // copy by reference, ok
s.val = "b";
Console.WriteLine(data[0].val); // "b"
是否有一种更简单的方法可以通过引用将字符串传递到集合中而不将其包装到类中? 我想将对象成员传递到集合中,如果对象发生更改,集合也应该更改,而无需编写额外的代码。
It seems that string is reference, but copied by value
List<string> data = new List<string>();
string s = "a";
data.Add(s); // copy by value??
s = "b";
Console.WriteLine(data[0]); // "a"
It also seems that class is reference copied by reference
class boxstring { public string val; }
List<boxstring> data = new List<boxstring>();
boxstring s = new boxstring { val = "a" };
data.Add(s); // copy by reference, ok
s.val = "b";
Console.WriteLine(data[0].val); // "b"
Is there a simpler way to pass string into collection by reference without wrapping it into class? I'd like to pass object member into collection and if the object is changed, the collection should be also changed without writing extra code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
字符串是不可变的,如果您希望容器中的对象发生更改,它们必须是可变的。因此,您必须像您一样将它们包装在一个类中。
Strings are immutable, if you want the objects in your container to change, they must be mutable. Therefore, you must wrap them in a class like you did.
字符串是不可变的。每当您为字符串变量分配新值时,每次都会创建一个新实例,这就是您看不到集合中更新的原因。
然而,.NET 已经提供了字符串的可变对应项,即“
StringBuilder
”。这对你有用 -Strings are immutable. Whenever you assign new value to string variable, a new instance is created everytime that's why you can't see the updates in your collection.
However, .NET already provide mutable counterpart of string i.e. "
StringBuilder
". This will work for you -这里有一个让你的代码更简单的想法:
那么只要你想通过引用获得字符串,你就可以使用 MyString 对象。因为我们有这些隐式运算符,你可以使用 MyString 而不是字符串
Here's an idea to make you code simpler :
then you can use MyString object whenever you want to have string by reference.since we have these implicit operator in place you can use MyString instead of string
您不能通过引用传递内在数据类型,它们始终通过值传递。
内部类型包括 Int32、String、Bool 等基本类型。
You cannot pass intrinsic data-types by reference, they are always passed by value.
Intrinsic types include basic types like Int32, String, Bool, etc..