Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/269.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#_Return - Fatal编程技术网

C# 返回不工作

C# 返回不工作,c#,return,C#,Return,我不明白为什么我不能从函数getstudentinformation访问studentinformation。代码如下: static void Main(string[] args) { getstudentinformation(); string firstname = studentinformation[0]; } static Array getstudentinformation() { Console.WriteLine("enter the stude

我不明白为什么我不能从函数
getstudentinformation
访问
studentinformation
。代码如下:

static void Main(string[] args)
{
    getstudentinformation();
    string firstname = studentinformation[0];
}

static Array getstudentinformation()
{
    Console.WriteLine("enter the student's first name: ");
    string firstname = Console.ReadLine();
    Console.WriteLine("enter the student's last name");
    string lastname = Console.ReadLine();
    Console.WriteLine("enter student's gender");
    string gender = Console.ReadLine();
    string[] studentinformation = { firstname, lastname, gender };
    return studentinformation;
}

Visual Studio无法识别数组,当我尝试构建代码时,出现了无法识别学生信息的错误。

您的代码是错误的。试试这个:

static void Main(string[] args)
    {
        string[] studentInformation = getstudentinformation();
        string firstname = studentinformation[0];
    }
    static string[] getstudentinformation()
    {
        Console.WriteLine("enter the student's first name: ");
        string firstname = Console.ReadLine();
        Console.WriteLine("enter the student's last name");
        string lastname = Console.ReadLine();
        Console.WriteLine("enter student's gender");
        string gender = Console.ReadLine();
        string[] studentinformation = { firstname, lastname, gender };
        return studentinformation;
    }

您没有将
getstudentinformation
的结果分配给任何变量,并且由于您尝试访问的变量在另一个作用域中声明,因此您无法访问它。

您的方法是正确的,错误的是如何使用它。这样做:

var firstname = getstudentinformation().GetValue(0);
但我建议不要使用这个数组类,例如按照NicoRiff建议的方式使用它,包括:

static string[] getstudentinformation()
主要用途如下:

var firstname = getstudentinformation()[0];
Array
您使用的类是每个数组的基类(
string[]
),因此您的字符串数组就是这个
Array
,但不是每个
Array
都是一个字符串数组,您可以从一个方向投射,但不能从另一个方向投射,更多信息请参见:


您的代码可以正常工作。它不是很漂亮,但它编译并返回数组。您得到的确切错误消息是什么?如果您能向他解释数组和字符串[]之间的区别,那就太好了。这段代码没有工作。如果您在发布答案之前检查答案,您可以看到,它将编译。@MaksimSimkin它怎么没有错,您确定您编译了他的代码而不是这个答案吗?正如回答者所说,当学生信息在内部声明时,您如何访问该信息?@MaksimSimkin该代码没有按预期工作。Main()中不存在studentinformation好的,Main中的调用是错误的,但方法本身不是,您可以将字符串[]强制转换为数组,这没有多大意义,但它可以工作。