如何获得可变字符串列表? [英] How to get a list of mutable strings?

查看:168
本文介绍了如何获得可变字符串列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面一段代码

  List<String> l = new List<String>();
  String s = "hello";
  l.Add(s);
  s = "world";

当我设置了一些断点并办理程序,执行的最后一行,在值之后该名单仍然你好而不是全球

When I set up some breakpoints and go through the program, after executing the last line, the value in the list is still hello instead of world.

难道不应该等于全球?不是字符串对象,而我不能只是插入一个指针到列表中?后来,如果我改变字符串指向一个不同的值(世界),为什么我的列表中仍然引用旧的价值?

Shouldn't it equal world ? Isn't a string an object, and am I not just inserting a pointer into the list? Later on if I change the string to point to a different value ("world"), why is my list still referencing the old value?

我怎样才能得到我想要的效果呢?
非常感谢!

How can I get my desired effect ? Thanks a lot!

推荐答案

字符串是不可变的,这样是行不通的。当您尝试设置进去,你居然指针下降到老的字符串,并创建引擎盖下一个新的。

Strings are immutable so that won't work. When you attempt to set into it, you actually drop the pointer to the old string and create a new one under the hood.

要取得预期的效果,创建一个类换行的字符串:

To get the desired effect, create a class that wraps a string:

public class SortOfMutableString
{
    public string Value {get;set;}

    public SortOfMutableString(string s)
    { 
        Value = s;
    }

    public static implicit operator string(SortOfMutableString s)
    {
        return s.Value;
    }

    public static implicit operator SortOfMutableString(string s)
    {
        return new SortOfMutableString(s);
    }
}

和您的列表中使用。然后引用将指向类,但你可以包含内部的字符串值。为了使其更好,覆盖铸造和绳子,让你甚至都不需要看到你所谈论到 SortOfMutableString

And use this in your list. Then references will point to the class, but you can contain the string value inside. To make it even better, override implicit casting to and from string so you don't even need to see that you are talking to a SortOfMutableString.

请参阅乔恩斯基特的答案无疑是有关字符串在C#中一个非常准确的解释,我还没有去打扰!

Refer to Jon Skeet's answer for undoubtedly a very accurate explanation about string's in C#, I'm not even going to bother!

替代类名:


  • PseudoMutableString

  • ICantBelieveItsNotMutable

  • HappyAndReferenceableString

这篇关于如何获得可变字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆