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

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

问题描述

如果字符串操作不会更改,在创建新实例例如落得个字符串的值,威尔;

If the string operation doesn't change the value of string, Will that end up in creation of new instance?Eg;

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



我知道在C#中的字符串和StringBuilder的区别。

i know the difference between string and stringbuilder in C#.

推荐答案

没有,新的实例将只有当字符串操作更改字符串变量中的值来创建。
它可以使用的 ObjectIDGenerator class.it的值得一读的这个完整的文章举证

No,New instance will be created only when string operation changes the value in string variable. it can be proved using 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 indicate whether 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天全站免登陆