Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#将字符串放入数组中_C#_Arrays_String - Fatal编程技术网

c#将字符串放入数组中

c#将字符串放入数组中,c#,arrays,string,C#,Arrays,String,这可能非常简单,但如何将字符串放置或转换为数组 我拥有的代码如下所示: public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string one; string[] two; one = "Juan"; two = {one}; // here is

这可能非常简单,但如何将字符串放置或转换为数组

我拥有的代码如下所示:

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string one;
        string[] two;

        one = "Juan";
        two = {one}; // here is the error

        HttpContext.Current.Response.Write(two);
    }
}
错误如下: 编译器错误消息:CS0029:无法将类型“string”隐式转换为“string[]”

谢谢你的帮助

替换这个:

two = {one}; // here is the error

从错误消息中可以清楚地看到出现错误的原因

见:

稍后在执行
Response.Write
时,您将得到
System.String[]
作为输出,因为
two
是一个数组。我想你需要所有的数组元素用分隔符分隔。您可以尝试:

HttpContext.Current.Response.Write(string.Join(",", two));

它将生成数组中由逗号分隔的所有元素。看起来您正在尝试对赋值使用初始化语法。这应该起作用:

two = new string[] {one};
或者只是

two = new [] {one};
因为编译器将推断您需要一个
字符串[]


我想你也会惊讶于
的反应生成…

您正在使用静态初始值设定项语法尝试向数组中添加项。那不行。您可以使用类似的语法分配一个值为
one
-
two=newstring[]{one}的新数组-或者您可以分配数组,然后通过赋值添加元素,如

    string[] two = new string[10];
    two[0] = one; // assign value one to index 0
如果您这样做,您必须进行一些边界检查,例如,以下内容将在运行时抛出一个
IndexOutOfRangeException

    string[] two = new string[10];
    int x = 12;
    two[x] = one; // index out of range, must ensure x < two.Length before trying to assign to two[x]
string[]two=新字符串[10];
int x=12;
两[x]=1;//索引超出范围,在尝试分配给两个[x]之前,必须确保x<2.Length
只有在同一行中声明数组变量时,语法(
{one}
)才有效。因此,这是可行的:

string one;

one = "Juan";
string[] two = {one};
初始化数组的一种更常见的方法是使用
new
关键字,并且可以选择推断类型,例如

string one;
string[] two;

one = "Juan";
// type is inferrable, since the compiler knows one is a string
two = new[] {one};
// or, explicitly specify the type
two = new string[] {one};
我通常在同一行上声明和初始化,并使用来推断类型,因此我可能会写:

var one = "Juan";
var two = new[] { one };

系统将显示以下内容:
在同一行中键入预期的
。谢谢你的快速回答。@JulianMoreno,试试
two=newstring[]{one}系统显示以下内容:
与'string.Join(string,string[])匹配的最佳重载方法有一些无效参数
@JulianMoreno,我的错,它应该是string
,“
,而不是character
,”
更新了答案它可以工作!还有
HttpContext.Current.Response.Write(string.Join(',',two)***)缺少括号中的“)”。谢谢你的快速帮助!
string one;
string[] two;

one = "Juan";
// type is inferrable, since the compiler knows one is a string
two = new[] {one};
// or, explicitly specify the type
two = new string[] {one};
var one = "Juan";
var two = new[] { one };