C# assign char and char array to string?(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数组分配给字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#将char和char数组分配给字符串?


- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 使用 rss + c# 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01