C#函数返回 [英] C# Function Returning

查看:90
本文介绍了C#函数返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI Everyone!



我可以在C#中将数组从函数返回到Main。因为我正在用C#编写一个用于学生管理的程序,并且在从Functi0n获取课程名称后,我只想将数据返回到主要使用循环中的主要然后显示。



请参阅下面的代码。


HI Everyone!

Is it Possible That I Return Array From Function To Main In C#. Because i am Writing A Program in C# for Student Management and after Taking The Course Name From The Functi0n I just Want to Return this array with Data Into The Main Then Show in THE Main Using Loop.

Please See the Below Code.

namespace Practice_Csharp_2
{
    enum constant
    {
        subject = 6,
    }
    class Program
    {
        static void Main(string[] args)
        {
            
            string[] course = new string[(int)constant.subject];
            int x;
            //Calling Function For Taking Student Course
            cou(course);
            Console.WriteLine("\nEntered Subject.\n");
            for (x = 0; x < (int)constant.subject; x++)
            {
                Console.WriteLine("Subjecrt {0} Is.", course[x]);
            }
            Console.ReadLine();
        }
        //Making New Function For Getting Course Name.
        static string cou(string[] course)
        {
            int x;
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("\n\t\t\tEnter Subject Name.");
            Console.ResetColor();
            for (x = 0; x < (int)constant.subject; x++)
            {
                Console.WriteLine("Enter Subject {0} Name.",x+1);
                course[x] = Convert.ToString(Console.ReadLine());
            }
//AT THIS POINT I GOT THE PROBLEM I WANT TO RETURN THIS ARRAY INTO THE MAIN PROGRAM USING RETURN STATEMENT .PLEASE GIVE ME SOLUTION IF YOU KNOW.
            return string[] course();
        }


推荐答案

您无需返回数组。

实际的数组项在函数体中被修改,你将在 Main 代码中看到这样的修改。
You don't need to return the array.
The actual array items are modified in the function body and you are going to see such modifications in the Main code.


看看你的函数声明:

static string cou(string [] course)

它返回一个字符串 - 不是一个数组字符串。将其更改为

static string [] cou(string [] course)

返回语句目前完全被破坏 - 只返回变量。

返回课程;

正如另一个答案中已经指出的那样,实际上并非如此必要的,因为数组中的更改也可以在您调用该函数的函数中看到。

即你也可以做一个简单的

static void cou(string [] course)

没有任何返回语句功能体。
Look at your function declaration:
static string cou(string[] course)
it returns a string - not an array of strings. Change it to
static string[] cou(string[] course)
The return statement is currently totally broken - only return the variable.
return course;
As already pointed out in another answer, that is actually not necessary as the changes in the array are also visible in the function from where you call that cou-function.
I.e. you could also do a simple
static void cou(string[] course)
without any return statement in the function body.


这篇关于C#函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆