为什么string str = new string(“abc”)不能通过编译器?

问题描述:

鉴于public String(char*)为什么我们不能使用以下语句?为什么string str = new string(“abc”)不能通过编译器?

string str = new string("aaa"); 

错误1

为 'string.String(字符*)' 最好的重载的方法匹配具有一些 无效 参数C:\ TEMP \ ConsoleApplication2 \ ConsoleApplication2 \ 19的Program.cs 26个ConsoleApplication2

错误2

参数1:不能从 '字符串' 转换为 '字符*' C:\ TEMP \ ConsoleApplication2 \ ConsoleApplication2 \的Program.cs 19 37 ConsoleApplication2

只需使用:

string str = "aaa"; 

你不需要new一个字符串。

“aaa”是一个字符串。这不是char *
char *unsafe代码一起使用。

+0

这是我需要的:) -thx – q0987 2011-06-01 20:50:24

您试图调用一个字符串作为参数的构造函数。

编译器告诉你没有字符串构造函数作为参数使用单个字符串。

+0

所以在C#中的“AAA”并不意味着一个char类型的*? – q0987 2011-06-01 20:48:32

+0

@ g0987 nope它始终是一个System.String,它是UTF-16编码的字符串 – 2011-06-01 20:50:01

因为这并不意味着在安全代码中使用...

在C#中,此构造函数定义只有在不安全代码的情况下。

来自:http://msdn.microsoft.com/en-us/library/6y4za026.aspx

如果您需要构建你可以只使用文字decleration字符串..

string str = "aaa"; 

类型char*是不安全的指针 - 一个对象不.Net托管框架的一部分。当您将代码中的文字字符串"aaa"置入时,这是一个托管对象。在C#中,string不是char*

必须看看这也许能解决您的疑问C# New String Constructor

unsafe public String(char*); 
     public String(char[]); 
unsafe public String(sbyte*); 
     public String(char, int); 
unsafe public String(char*, int, int); 
     public String(char[], int, int); 
unsafe public String(sbyte*, int, int); 
unsafe public String(sbyte*, int, int, Encoding); 
+0

我在发布我的问题之前检查了这些信息。从这个主题阅读消息后,我得到了基本的想法。 - thx – q0987 2011-06-01 20:49:53

+0

@ q0987 - 正如你看到的文档,你需要传递字符数组,你不能传递字符串值...我不是很好,你传递了字符串,如果你已经有了它的信息.... – 2011-06-01 20:52:32