C# 如何在c中调用main中的字符串数组方法#
我是c#的新手,我不明白为什么这不起作用。我得到的错误主要是subjects(),如下所述 我的代码如下:C# 如何在c中调用main中的字符串数组方法#,c#,C#,我是c#的新手,我不明白为什么这不起作用。我得到的错误主要是subjects(),如下所述 我的代码如下: class Program { static void Main(string[] args) {string sub; // string brd; brd = board(); sub = subjects(); // Error //Console.Wr
class Program
{
static void Main(string[] args)
{string sub;
// string brd;
brd = board();
sub = subjects(); // Error
//Console.WriteLine(brd);
Console.WriteLine(sub);
Console.ReadLine();
}
public static string[] subjects()
{
Console.WriteLine("Please Enter How many Subject Do you Want to input");
int limit = System.Convert.ToInt32(Console.ReadLine());
string[] Subjects = new string[limit];
int[] index = new int[limit];
for (limit = 0; limit <= index.Length; limit++)
{
Console.WriteLine("Please Enter Subject Name " + limit + 1);
Subjects[limit] = Console.ReadLine();
}
return Subjects;
}
}
类程序
{
静态void Main(字符串[]参数)
{string sub;
//串级制动;
brd=电路板();
sub=subjects();//错误
//控制台写入线(brd);
控制台写入线(sub);
Console.ReadLine();
}
公共静态字符串[]主题()
{
Console.WriteLine(“请输入要输入多少主题”);
int limit=System.Convert.ToInt32(Console.ReadLine());
字符串[]主题=新字符串[限制];
int[]索引=新的int[限制];
对于(limit=0;limit请尝试以下方法:
string[] sub = subjects();
与此相反:
string sub;
sub = subjects();
因为您正在获取数组字符串并将其传递给普通字符串。您正在将sub
定义为字符串(string sub
)但是方法subjects正在返回字符串数组。因此
sub无法保存该方法的返回值。您必须将
sub的返回类型从string更改为
string[]`。这意味着声明应如下所示:
string[] sub = subjects();
var sub = subjects();
或者用更简单的方法,你可以这样做:
string[] sub = subjects();
var sub = subjects();
因此,编译器将根据该方法的返回值自动选择返回类型。如果您对此类赋值中的数据类型感到困惑,您可以var
让编译器根据这些值决定数据类型。请参阅/**/comment
class Program
{
static void Main(string[] args)
{
string sub; /*1. Remove this line*/
// string brd;
brd = board();
sub = subjects(); /*2. string[] sub = subjects();*/
//Console.WriteLine(brd);
Console.WriteLine(sub);
Console.ReadLine();
}
public static string[] subjects()
{
Console.WriteLine("Please Enter How many Subject Do you Want to input");
int limit = System.Convert.ToInt32(Console.ReadLine());
string[] Subjects = new string[limit];
int[] index = new int[limit]; /*3. Remove this line -> Redundant*/
/*4. Change variable `limit` to `i`*/
for (int i = 0; i <= limit; i++)
{
Console.WriteLine("Please Enter Subject Name " + i + 1);
Subjects[i] = Console.ReadLine();
}
return Subjects;
}
}
类程序
{
静态void Main(字符串[]参数)
{
字符串sub;/*1.删除此行*/
//串级制动;
brd=电路板();
sub=subjects();/*2.string[]sub=subjects()*/
//控制台写入线(brd);
控制台写入线(sub);
Console.ReadLine();
}
公共静态字符串[]主题()
{
Console.WriteLine(“请输入要输入多少主题”);
int limit=System.Convert.ToInt32(Console.ReadLine());
字符串[]主题=新字符串[限制];
int[]index=new int[limit];/*3.删除此行->冗余*/
/*4.将变量'limit'更改为'i'`*/
对于(int i=0;i现在代码中没有任何错误,但在运行时错误编译器没有打印(sub)
控制台写入线(sub);
Console.ReadLine();您遇到了什么错误?发布问题时,您应该格式化代码以便于阅读(遵守C#惯例),您应该以不同的方式向我们提供编译器发出的确切错误消息,并且您应该在代码中指出它。希望这是一种错误的回答方法,在代码中添加正确的答案并给出解释。您的代码仍然显示问题中提到的错误。