在函数C#中返回关键字

时间:2014-05-19 08:25:29

标签: c#

我有一个关于C#函数输出或返回的简单问题。 我试图了解,然后在互联网上看,但没有答案! 你可以向我解释一下多个return语句的功能是做什么的。例如:

using UnityEngine;
using System.Collections;
using System;
using lj;

namespace ljack
{

public class joystick : MonoBehaviour {

public static float a;      
public static float b;


void Start(){


      int[] idList = GetAllLabJacks();      

 if (idList.Length == 0)
                Debug.Log("No LabJacks found!");
            else
            {
                // List the IDs of LabJacks we found
                foreach (int id in idList)
                {
                   Debug.Log("id=" + id);



                }
            }           

        }       


void Update(){


 // Read in the analog input from channel 0
            // and output the result


            int ljID = 2;
            int overVoltage = 0;
            float voltage1 = 0.0f;

            int result = LabJack.EAnalogIn(ref ljID, 0, 0, 0, ref overVoltage, ref voltage1);

              //Debug.Log("voltage1="+ voltage1);


            float voltage2=0.0f;
             result = LabJack.EAnalogIn(ref ljID, 0, 1, 0, ref overVoltage, ref voltage2);

            //Debug.Log("voltage2="+ voltage2);



            a=voltage1;
            b=voltage2;




}

 // This returns an array of all the local IDs which we use.
        //
public static int[] GetAllLabJacks()
        {
            // Make sure we allocate space for what is passed
            int[] productIDList = new int[127];
            int[] serialNumList = new int[127];
            int[] localIDList = new int[127];
            int[] powerList = new int[127];
            int[,] calMatrix = new int[127, 20];
            int numFound = 0;
            int reserved1 = 0, reserved2 = 0;

            // Call the ListAll function.  We must use the keyword ref for parameters 
            // that aren't arrays that return data
            int result = LabJack.ListAll(productIDList, serialNumList, localIDList,
                powerList, calMatrix, ref numFound, ref reserved1, ref reserved2);



            int[] ljs = new int[numFound];
            int i = 0;

            // count how many we found and set
            // the array which will be returned
            // to contain valid IDs
            foreach (int id in localIDList)
            {
                if (id != 9999)
                {
                    ljs[i] = id;
                    ++i;
                }
            }

            // return that array
            return ljs;
        }       

 // This is our function that read's analog input
public static float Getjoyst(){


            return a;
            return b;
        }            

}
} 

它会返回a或b,还是一个接一个?

look for this code also

using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.IO;


public class menu : MonoBehaviour {


// name .. of the player

public  string nom;   
public  string pathologie;
public  string comment;


// v is used to display the value of( niveau de vitesses)

public static int v;        


//pour pouvoir copier les donnees dans le script mouvement, tracction et central

public static string playnom;
public static string playpathologie;
public static string playcomment;   
public static string envir; 
public static string main;  
public static bool Activer;
public static bool Desactiver;  


// le type du fauteuil  

public static bool Propultion;  
public static bool Central;
public static bool Traction;


// obstacles

public static bool  Serie1; 
public static bool  Serie2;
public static bool  Serie1et2;


//coté de commande

public static bool aucun;
public static bool gauche;


//env

public static bool droite;  
public bool exterieur;
public bool cerah;
public bool nan;
public bool crnf;


// mouvement des obstacles

public  bool activer;
public  bool desactiver;


// used to display the text

public  GUIText fauteuil; // used to display the text fauteuil
public GUIText vitesse;  // used to display the text vitesse
public GUIText obstacles; // used to display the text obstacles
public GUIText mouv;    // used to display the text obstacles en mouvement
public GUIText env;    // used to display the text Envirennement

public GUIText info;    
public GUIText cotecommande;


// pour les indications et les affichage

public GUIText indication;
public GUIText indication1; 
public GUIText indication2; 
public GUIText niveau;   //used to display the text niveau
public GUIText important;   


//importation des variables

public bool etat1; // pour importer des variables bool de mouvement
public bool pro;    
public bool etat2; // pour importer des variables bool de central
public bool cen;    
public bool etat3;// pour importer des variables bool de traction
public bool tra;    


public string information1; // pour importer des variables de type string de mouvement
public string information2; // pour improter des variables de type string de central    
public string information3; // pour importer des variables de type string de traction           





void OnGUI(){


//  premiers bouton du menu principal

    if(GUI.Button(new Rect(10,50,200,25),"Information utilisateur")){

            main="Information utilisateur";

        }


    if (GUI.Button(new Rect(10,100,200,25),"Fauteuil")) {

            main="Fauteuil";
        }


    if(GUI.Button(new Rect(10,150,200,25),"Environnement")){

            main="Envirennement";
        }   

    if(GUI.Button(new Rect(10,200,200,25),"Raccourcis clavier")){

            main="Raccourcis clavier";

        }


    if(GUI.Button(new Rect(10,250,200,25),"Commencer la simulation")){

            main="Commancer la sim";

        }


    if(GUI.Button(new Rect(10,300,200,25),"Quitter")){

            main="Quitter";
            Application.Quit();

        }       


//--------------------------------------------------------------------------------- 


if (main=="Information utilisateur"){

            // si le buttoninfo utili est appuyé

            GUI.Label(new Rect(300,100,100,30),"Nom: ");  //On ecrit sur un label le mot nom
            nom=GUI.TextField(new Rect(350,100,200,30), nom); //reservation d'une case rectangulaire pour l'ecriture d'une chaine de caractères 


            GUI.Label(new Rect(300,150,100,30),"pathologie: ");
            pathologie=GUI.TextField(new Rect(370,150,200,30), pathologie);


            GUI.Label(new Rect(300,200,100,30),"Commentaires: ");
            comment=GUI.TextField(new Rect(300,250,300,100), comment);


            info.text="Informations utilisateur";

            indication2.text="Renseignez les informations puis appuyez sur OK";


            if(GUI.Button(new Rect(300,400,100,25),"ok")){

                if (nom==""||pathologie==""){

                    important.text="nom est pathologie obligatoires ";

                }

                else
                    {   
                        playnom=nom;
                        playpathologie=pathologie;
                        playcomment=comment;

                        main="";
                        important.text="";

                }
            }           

}       



            else{

                info.text="";
                indication2.text="";

            }




//-----------------------------------------------------------------------------------------     

if(main=="Fauteuil"){ 

// si le boutton fauteuil allors

//affichage des textes  

        fauteuil.text=main;
        vitesse.text="vitesse Du Fauteuil"; 
        indication.text="Choisissez la configuration du fauteil puis appuyez sur OK";
        cotecommande.text="cote de commande";   


        //criation des bouttons

        if(GUI.Toggle(new Rect(300,100,150,25),Propultion,"Propultion")){

                Propultion=true;
                Central=false;
                Traction=false;

            }


        if(GUI.Toggle(new Rect(450,100,150,25),Central,"Central")){

                Propultion=false;
                Central=true;
                Traction=false;


            }

        if(GUI.Toggle(new Rect(600,100,150,25),Traction,"Traction")){

                Propultion=false;
                Central=false;
                Traction=true;

            }


        if(GUI.Toggle(new Rect(300,300,150,25),gauche,"gauche ")){

                gauche=true;
                droite=false;

            }       


        if(GUI.Toggle(new Rect(450,300,150,25),droite,"droite")){

                gauche=false;
                droite=true;

            }


        if(GUI.Button(new Rect(300,400,100,25),"ok")){

                main="";

            }


//si le buton + alors on augmente le niveau     

        if(GUI.Button(new Rect(300,200,25,25),"-")){

        v=v-1;

        }


// si le bouton - alors on deminue le niveau    

        if(GUI.Button(new Rect(450,200,25,25),"+")) {

        v=v+1;

        }

        niveau.text="niveau "+v;

}   


else{ 

        // effacer les texte si le bouton fauteil n'est pa appuyé

        fauteuil.text="";
        vitesse.text="";    
        niveau.text=""; 
        indication.text=""; 
        cotecommande.text="";

}   


//----------------------------------------------------------------------------------------------------------------

if (main=="Envirennement"){ 

// si le button envirennement alors

            aucun=true;
            desactiver=true;
            obstacles.text="Obstacles";
            indication1.text="Choisissez les obstacles et l'envirennement puis appuyez sur OK";
            env.text="Envirennement";

//les obstacles

             if(GUI.Toggle(new Rect(300,100,150,25),Serie1,"Serie 1(cones)")){

                Serie1=true;
                Serie2=false;
                Serie1et2=false;
                aucun=false;
                mouv.text="";   
                desactiver=true;
                activer=false;

            }


            if(GUI.Toggle(new Rect(450,100,150,25),Serie2,"Serie 2")){

                Serie1=false;
                Serie2=true;
                Serie1et2=false;
                aucun=false;
                mouv.text="Obstacles en mouvement"; 

                //mouvement des obstacles

                if(GUI.Toggle(new Rect(300,200,100,25),activer,"Activer")){

                activer=true;
                desactiver=false;

                }

                if(GUI.Toggle(new Rect(450,200,100,25),desactiver,"Desactiver")){

                desactiver=true;
                activer=false;

                }           

            }   


            if(GUI.Toggle(new Rect(600,100,150,25),Serie1et2,"Serie 1 et 2")){

                Serie1=false;
                Serie2=false;
                Serie1et2=true;
                aucun=false;
                mouv.text="Obstacles en mouvement"; 

                //mouvement des obstacles

                if(GUI.Toggle(new Rect(300,200,100,25),activer,"Activer")){

                activer=true;
                desactiver=false;

                }

                if(GUI.Toggle(new Rect(450,200,100,25),desactiver,"Desactiver")){

                desactiver=true;
                activer=false;

                }   

            }


            if(GUI.Toggle(new Rect(750,100,150,25),aucun,"Aucun obstacle")){

                Serie1=false;
                Serie2=false;
                Serie1et2=false;
                aucun=true;
                desactiver=true;
                activer=false;
                mouv.text="";

            }


//envirennement 


            if(GUI.Toggle(new Rect(300,300,100,25),exterieur,"Exterieur")){

            exterieur=true;
            cerah=false;
            nan=false;
            crnf=false; 

            }

            if(GUI.Toggle(new Rect(450,300,100,25),cerah,"CERAH")){

            exterieur=false;
            nan=false;
            cerah=true;
            crnf=false;

            }   

            if(GUI.Toggle(new Rect(600,300,100,25),nan,"NANCY")){

            exterieur=false;
            cerah=false;
            nan=true;
            crnf=false;

            }

            if(GUI.Toggle(new Rect(750,300,100,25),crnf, "CRNF")){
            exterieur=false;
            cerah=false;
            nan=false;
            crnf=true;  

            }


            if(GUI.Button(new Rect(300,400,100,25),"ok")){

                mouv.text="";
                main="";
                Activer=activer;
                Desactiver=desactiver;

            }


}       


else{

obstacles.text="";
indication1.text="";
env.text="";

} 

//------------------------------------------------------------------------------------------------------------      


if(main=="Commancer la sim"){

            if (nom==""||pathologie==""){

                important.text="nom et pathologie obligatoires ";
            }

            else

            {

                if (cerah){

                Application.LoadLevel("scene1");
                envir="CERAH";

                }   



                if (exterieur){

                Application.LoadLevel("scene2");
                envir="exterieur";

                }   



                if (nan){

                Application.LoadLevel("scene5");
                envir="NANCY";

                }       

                if(crnf){

                Application.LoadLevel("scene4");
                envir="CRNF";   

                }

            }

}


//-------------------------------------------------------------------------------------------------------------------       

if(main=="Raccourcis clavier"){

        GUI.Label(new Rect(300,50,600,25),"Z  E  R  T  Y  U: Changer la position de la camera  ");  


        GUI.Label(new Rect(300,75,500,25),"C  V  N  B : type d'obstacles .  "); 
            GUI.Label(new Rect(350,100,500,25),"C : Serie 1 et 2 .");   
            GUI.Label(new Rect(350,125,500,25),"V:  Serie 2 (humain).");    
            GUI.Label(new Rect(350,150,500,25),"N:  Serie 1 (cones)."); 
            GUI.Label(new Rect(350,175,500,25),"B: Aucun obstacle.");   


        GUI.Label(new Rect(300,200,500,30),"A  D: Activer ou desactiver le mouvement des obstacles serie2. ");      
            GUI.Label(new Rect(350,225,500,25),"A: Activer.  ");    
            GUI.Label(new Rect(350,250,500,25),"D: Desactiver. ");  


        GUI.Label(new Rect(300,275,500,25),"1  2  3  4  5: Les niveaux de vitesses.   ");   
            GUI.Label(new Rect(350,300,500,25),"1: 02 KM/H. ");     
            GUI.Label(new Rect(350,325,500,25),"2: 04 KM/H. "); 
            GUI.Label(new Rect(350,350,500,25),"3: 06 KM/H. "); 
            GUI.Label(new Rect(350,375,500,25),"4: 08 KM/H. "); 
            GUI.Label(new Rect(350,400,500,25),"5: 10 KM/H.");      


        GUI.Label(new Rect(300,425,500,25),"S  Q:Enregistrement des donnees dans un fichier texte. ");  
            GUI.Label(new Rect(350,450,500,25),"S: Commencer ou Reprendre l'enregistrement ");  
            GUI.Label(new Rect(350,475,500,25),"Q: Arret de l'enregistrement. ");   


        GUI.Label(new Rect(300,500,500,25),"F  O : Ouverture et fermeture des portes de l'ascenseur de l'envenimement C.R.N.F. ");      
            GUI.Label(new Rect(350,525,500,25),"O: Ouverture des portes de l'ascenseur. "); 
            GUI.Label(new Rect(350,550,500,25),"F: Fermetures des portes de l'ascenseur. ");    


        GUI.Label(new Rect(300,575,1450,25),"P: Pause et Retour au menu principal");    



}       


}   


void Start()

{

        // importation des variables

        etat1=mouvement.typefaut();
        pro=mouvement.PROPULTION;

        etat2=central.typefaut();
        cen=central.CENTRAL;

        etat3=traction.typefaut();
        tra=traction.TRACTION;


        if(pro){

        information1=mouvement.utilis();
        nom=mouvement.NOM;  
        pathologie=mouvement.PATHOLOGIE;
        comment=mouvement.COMMENT;  

        }


        if(cen){

        information2=central.utilis();
        nom=central.NOM;    
        pathologie=central.PATHOLOGIE;
        comment=central.COMMENT;        

        }


        if(tra){

        information3=traction.utilis();
        nom=traction.NOM;   
        pathologie=traction.PATHOLOGIE;
        comment=traction.COMMENT;   

        }


                playnom=nom;
                playpathologie=pathologie;
                playcomment=comment;


        // choix par defaut

                Propultion=true;
                Central=false;
                Traction=false;
                gauche=false;
                droite=true;
                v=3;
                Serie1=false;
                Serie2=false;
                Serie1et2=false;
                aucun=true;
                desactiver=false;
                activer=true;

}   


void Update ()

    {

//limiter les niveau entre 1 et 10      

        if (v>=5){
            v=5;
        }

        if(v<=1){
            v=1;
        }


// for saving the data in txt file

        playnom=nom;
        playpathologie=pathologie;
        playcomment=comment;    
        Time.timeScale=0; // temps en arret

}


public  static string Getnom(){  

//pour la recuperation des données de type string dans le script mouvement

        return playnom;
        return playpathologie;
        return playcomment; 
        return envir;
        return main;

}


public static bool Getetat(){   

//pour la recuperation des données de type bool dans le script mouvement

        return  Activer;
        return  Desactiver;
        return  Serie1;
        return  Serie2;
        return  Serie1et2;
        return  aucun;
        return  Propultion;
        return  Central;
        return  Traction;
        return  gauche;
        return droite;

}


public static int Getvit(){

        return v;


}   


}

4 个答案:

答案 0 :(得分:1)

返回指令序列中第一个执行的return语句。所以这将返回a。通常只有在某种条件决定返回哪一条时才会看到多个return语句。

答案 1 :(得分:1)

在这种情况下,永远不会执行

return b;。函数执行将在return a;结束,a的值将返回到调用代码。然后程序将从它调用此GetValue()函数的位置继续。

其他人指责你没有做足够的研究。我认为你只是没有足够的技能来执行它。您可以通过各种方式查看正在执行的程序,例如通过调试它(设置一个断点,然后单步调试以查看发生的情况)或暂时使用能够让您知道正在进行的操作的代码。例如:

Console.WriteLine('before return a');
return a;
Console.WriteLine('after return a, before return b');
return b;

调用函数时也一样。熟悉这些主题。并享受编程乐趣: - )

答案 2 :(得分:1)

如果您的方法中有条件,则只有多个return语句才有意义。

示例:

public static float GetValue() {
    if (a) {
        return x;
    }
    else {
        return y;
    }
}

答案 3 :(得分:0)

有些情况下,多个return语句在C#中有效。条件退货的thakrage's example是一个。

另一个是你真正想要在列表中返回多个号码的地方。这可以通过在方法中构造列表,添加项目然后返回它来实现,或者通过涉及可枚举集合的更高级技术来实现,如下所示:

public static IEnumerable<float> GetValues()
{
    // …
    yield return a;
    yield return b;
}

用法通常是循环,显式如下:

foreach (float value in GetValues())
    // …

或隐式地将其传递给另一个对可枚举集合进行操作的方法:

float sumOfSquares = GetValues().Sum(f => f * f);

从你的问题我强烈怀疑这是你想知道的,但它是你将来可能遇到它的另一个例子。