C#将char和char数组分配给字符串?

C# assign char and char array to string?(C#将char和char数组分配给字符串?)
本文介绍了C#将char和char数组分配给字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        char character = 'c';
        string str = null;
        str = character.ToString();//this is ok

        char[] arrayChar = { 'a', 'b', 'c', 'd' };
        string str2 = null;
        str2 = string.Copy(arrayChar.ToString());//this is not ok
        str2 = arrayChar.ToString();//this is not ok.

我正在尝试将 char 数组转换为字符串,但最后两次尝试不起作用.我找到的其他来源,他们必须创建新的字符串类型,但我不知道为什么.谁能给我一点解释,谢谢.

I'm trying to converting char array to string, but the last two attempts don't work. Other source I found and they have to create new string type, but I don't know why. Can someone give me little explaination, thanks.

推荐答案

你需要构造一个新的字符串.

You need to construct a new string.

执行 arrayChar.ToString() 调用 char[] 类型的ToString"方法,该方法不会重载以从字符构造字符串,而是构造一个指定类型为字符数组的字符串.这不会给你你想要的行为.

Doing arrayChar.ToString() calls the "ToString" method for the char[] type, which is not overloaded to construct a string out the characters, but rather to construct a string that specifies that the type is an array of characters. This will not give you the behavior that you desire.

然而,通过 str2 = new string(arrayChar); 构造一个新字符串,会得到你想要的行为.

Constructing a new string, via str2 = new string(arrayChar);, however, will give you the behavior you desire.

问题在于,在 C# 中(与 C++ 不同),字符串与字符数组不同.这是两种截然不同的类型(即使它们可以表示相同的数据).字符串可以枚举为字符(String 实现 IEnumerable<Char>),但就 CLR 而言,它与字符的类型不同.进行转换需要代码在两者之间进行转换——字符串构造函数提供了这种机制.

The issue is that, in C# (unlike C++), a string is not the same as an array of characters. These are two distinctly different types (even though they can represent that same data). Strings can be enumerated as characters (String implements IEnumerable<Char>), but is not, as far as the CLR is concerned, the same type as characters. Doing a conversion requires code to convert between the two - and the string constructor provides this mechanism.

这篇关于C#将char和char数组分配给字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)