【问题标题】:Are string arrays immutable in C#?字符串数组在 C# 中是不可变的吗?
【发布时间】:2020-02-19 17:19:10
【问题描述】:

我有点困惑。我知道字符串是不可变的,但是字符串数组呢?

每当我向一个空数组添加一些东西时,它是否会创建该数组的一个新实例?

当我改变它的东西时怎么样?

string[] array = new string[5];

array[0] = "my favourite string"; //does it create a new instance of the array here?
array[0] = "changed that"; //how about now?

【问题讨论】:

  • 数组不是不可变的。
  • 数组实例(及其内存)是在string[] array = new string[5];这一行使用new操作符时创建的,详情可以查看specs
  • 谢谢!对于这些初学者问题,我深表歉意
  • System.Collections.Immutable中有不可变集合
  • 要尽可能的挑剔:任何 empty 数组都是不可变的,并且它本身就很有用。但是任何非空数组都是可变的。

标签: c# arrays


【解决方案1】:

这是您的代码的IL ..

IL_0000:  nop         
IL_0001:  ldc.i4.5    
IL_0002:  newarr      System.String
IL_0007:  stloc.0     // array
IL_0008:  ldloc.0     // array
IL_0009:  ldc.i4.0    
IL_000A:  ldstr       "my favourite string"
IL_000F:  stelem.ref  
IL_0010:  ldloc.0     // array
IL_0011:  ldc.i4.0    
IL_0012:  ldstr       "changed that"
IL_0017:  stelem.ref  
IL_0018:  ret

如您所见,数组只有一次instantiated

【讨论】:

    猜你喜欢
    • 2013-04-14
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 2015-04-15
    • 2011-08-06
    • 1970-01-01
    相关资源
    最近更新 更多