简体   繁体   English

如果将C#字符串与F#analogue进行比较,为什么C#字符串的标题为“不可变”?

[英]Why does C# string have a title “Immutable” if to compare it with F# analogue?

I have read the older topics like those ones: 我已经阅读了那些较旧的主题:

But, I can't understand the meaning of the word immutable , if to compare it with the F# analogue: 但是,如果将它与F#analogue进行比较,我无法理解immutable这个词的含义:

open System
let data = "London"
data <- "123"
Console.WriteLine data

This one won't compile due the next reason: 由于下一个原因,这个将无法编译:

error FS0027: This value is not mutable. 错误FS0027:此值不可变。 Consider using the mutable keyword, eg 'let mutable data = expression'. 考虑使用mutable关键字,例如'let mutable data = expression'。

So... If to compare the F# behaviour with the C# one, seems to be F# has the real meaning of immutability or I don't understand the real meaning of this term... 所以...如果要比较F#行为和C#one,似乎F#具有不变性的真正含义,或者我不明白这个术语的真正含义......

Let's look at the C# variant: 我们来看看C#变体:

class Program
{
    static void Main()
    {
        var a = "London";
        a = "123";
        System.Console.WriteLine(a);
    }
}

The output will be: 123 . 输出将是: 123

Let's take information from the next article: Why are the strings immutable in .NET? 让我们从下一篇文章中获取信息: 为什么字符串在.NET中是不可变的?

字符串附加

Honestly, if to look at this picture and compare it with the F# variant, I can't see the immutability... But also, I understand, that over 100+ people at SO (questions were published at the top of this question) can't be wrong and give the wrong name for such meaning. 老实说,如果要查看这张图并将其与F#变体进行比较,我看不到不变性......但是,据我所知,SO上有超过100人(问题发表在这个问题的顶部)不能错,并为这种意义给出错误的名称。

Please, tell me why has been the C# string called immutable , if I can change its value? 请告诉我为什么C#字符串名为immutable ,如果我可以更改它的值? And if to compare it with the F# sample, the results are different for the single meaning. 如果要将其与F#样本进行比较,则单个含义的结果会有所不同。

You are confusing the immutability of the variable in F# with the immutability of the object in C#. 您将F#中变量的不变性与C#中对象的不变性混淆起来。

In C#, you can change which object representing a string a variable is pointing at. 在C#中,您可以更改表示变量指向的字符串的对象。 But you can't change anything about that object, hence the object is immutable. 但是你不能改变关于那个对象的任何东西,因此对象是不可变的。

In F#, you cannot change which value a variable has, so the variable is also immutable. 在F#中,您无法更改变量具有的值,因此该变量也是不可变的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM