How to do String.Copy in .net core?

时光毁灭记忆、已成空白 提交于 2019-12-13 14:01:24

问题


In porting a .net framework app to .net core app, there are some uses of String.Copy to copy strings. But it looks this method is removed from .net core, so how would you copy a string in .net core app, and as a result, it is not present in uwp too. Does assignment string b = a; in .net core means something different as in .netframework?

The copy is used in this code:

public DataDictionary(DataDictionary src)
        :this()
    {
        this.Messages = src.Messages;
        this.FieldsByName = src.FieldsByName;
        this.FieldsByTag = src.FieldsByTag;
        if (null != src.MajorVersion)
            this.MajorVersion = string.Copy(src.MajorVersion);
        if (null != src.MinorVersion)
            this.MinorVersion = string.Copy(src.MinorVersion);
        if (null != src.Version)
            this.Version = string.Copy(src.Version);
    }

回答1:


Assignment of a string is something else than creating a copy. a = b just sets the reference of both variables to the same memory segment. string.Copy actually copies the string and thus the references are not the same any more.

I doubt however if you need string.Copy. Why would you want to have another reference? I can't think of any common cases you ever want this (unless you are using unmanaged code). Since strings are immutable, you can't just change the contents of the string, so copying is useless in that case.


Given your update with the code that uses string.Copy, I would say it is not useful to use string.Copy. Simple assignments will do if you use DataDictionary in managed code only.




回答2:


This is not as elegant as string.Copy(), but if you do not want reference equality for whatever reason, consider using:

string copiedString = new string(stringToCopy.ToCharArray());



回答3:


string newstring = $"{oldstring}";



来源:https://stackoverflow.com/questions/41758338/how-to-do-string-copy-in-net-core

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!