当C#中的字符串不变时,字符串的可变性 [英] Mutability of string when string doesn't change in C#

查看:121
本文介绍了当C#中的字符串不变时,字符串的可变性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果string操作没有更改string的值,那将最终创建一个新实例吗?

If the string operation doesn't change the value of string, will that end up in creation of a new instance?

例如,

string str = "foo";
str += "";

我知道C#中的string和StringBuilder之间的区别.

I know the difference between string and StringBuilder in C#.

推荐答案

否,仅当字符串操作更改字符串变量中的值时,才会创建新实例.

No, a new instance will be created only when the string operation changes the value in the string variable.

可以使用这篇完整的文章作为证明.

It can be proved using the ObjectIDGenerator class. It's worth reading this complete article for proof.

using System;
using System.Text;
using System.Runtime.Serialization;

namespace StringVsStringBuilder
{
    class Program
    {
        static void Main(string[] args)
        {
            ObjectIDGenerator idGenerator = new ObjectIDGenerator();
            bool blStatus = new bool();
            // blStatus indicates whether the instance is new or not
            string str = "Fashion Fades,Style Remains Same";
            Console.WriteLine("Initial state");
            Console.WriteLine("str = {0}", str);
            Console.WriteLine("Instance id: {0}", idGenerator.GetId(str, out blStatus));
            Console.WriteLine("This is new instance: {0}", blStatus);
            // A series of operations that won't change value of str
            str += "";

            // Try to replace character 'x' which is not present in str so no change
            str = str.Replace('x', 'Q');

            // Trim removes whitespaces from both ends so no change
            str = str.Trim();
            str = str.Trim();
            Console.WriteLine("\nFinal state");
            Console.WriteLine("str = {0}", str);
            Console.WriteLine("Instance id: {0}", idGenerator.GetId(str, out blStatus));
            Console.WriteLine("This is new instance: {0}", blStatus);
            Console.ReadKey();
        }
    }
}

这篇关于当C#中的字符串不变时,字符串的可变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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