Procediment Execució d’un programa de C # en Visual StudioHow to: Run a C # program in Visual Studio

  • 10/16/2019
  • Temps de lectura: 6 minuts
    • g
    • o

el que heu de fer per executar un programa depèn de el punt de partida, de el tipus de programa, aplicació o servei, i de si vol que s’executi en el depurador o no.What you need to do to run a program depends on what you’r starting from, what type of program, app, or service it is, and whether you want to run it under the debugger or not. En el cas més simple, si té un projecte obert en Visual Studio, pot compilar i executar prement Ctrl + F5 (Iniciar sense depurar) o F5 (Inicia amb depuració), o bé pressionant la fletxa de color verd (botó Inicia) de la barra d’eines principal de Visual Studio.In the simplest casi, when you have a project open in Visual Studio, build and run it by pressing Ctrl + F5 (Start without debugging) or F5 (Start with debugging), or press the green arrow (Start Button) on the main Visual Studio toolbar.

Captura de pantalla en què es mostra el botó Inicia

Inici a partir d’un proyectoStarting from a project

si té un projecte de C # (arxiu .csproj), pot executar si és un programa ejecutable.If you have a C # project (.csproj file), then you can run it, if it is a runnable program. Si un projecte conté un arxiu de C # amb un mètode Main i el seu resultat és un executable (EXE), el més probable és que s’executi si es compila correctamente.If a project contains a C # file with a Main method, and its output is an executable (EXE), then most likely it will run if it builds successfully.

Si ja té el codi de el programa en un projecte de Visual Studio, obriu el proyecto.If you already have the code for your program in a project in Visual Studio, open the project. Per obrir el projecte, feu doble clic o premeu a l’arxiu .csproj des de l’Explorador d’arxius de Windows o, en Visual Studio, trieu Obrir un projecte, cerqueu el fitxer de projecte (.csproj) i selecciónelo.To open the project, double-click or tap on the .csproj from the Windows file Explorer, or from Visual Studio, choose Open a project, browse to find the project (.csproj) file, and choose the project file.

Una vegada que es carreguin els projectes en Visual Studio, premeu Ctrl + F5 (Iniciar sense depurar) o utilitzeu el botó Inicia de color verd de la barra d’eines de Visual Studio per executar el programa.After the projects loads in Visual Studio, press Ctrl + F5 (Start without debugging) or use the green Start button on the Visual Studio toolbar to run the program. Si hi ha diversos projectes, el que tingui el mètode Main s’ha d’establir com a projecte de inicio.If there are múltiple projects, the one with the Main method must be setembre as the startup project. Per establir el projecte d’inici, feu clic amb el botó dret en un node de projecte i triï Establir com a projecte de inicio.To setembre the startup project, right-click on a project node, and choose setembre es startup project.

Establiment d'el projecte d'inici

Visual Studio intenta compilar i executar el proyecto.Visual Studio Attempts to build and run your project. Si hi ha errors de compilació, veurà el resultat de la compilació en la finestra Sortida i els errors en la finestra Llista d’errores.If there are build errors, you see the build output in the Output window and the errors in the Error List window.

Si la compilació es realitza correctament, l’aplicació s’executarà de la forma adequada per al tipus de proyecto.If the build succeeds, the app runs in a way that ‘s appropriate for the type of project. Les aplicacions de consola s’executen en una finestra de terminal, les d’escriptori de Windows s’inicien en una finestra nova, les aplicacions web s’inicien en l’explorador (provenen del IIS Express), etc.Console apps run in a terminal window, Windows desktop apps start in a new window, web apps start in the browser (hosted by IIS Express), and so on.

Inici a partir de códigoStarting from code

Si va a començar a partir d’un llistat de codi, un arxiu de codi o un nombre petit d’arxius, assegureu-vos primer que el codi que vol executar prové d’un origen de confiança i és un programa ejecutable.If you’r starting from a code listing, code file, or a small number of files, first make sure the code you want to run is from a trusted source and is a runnable program.Si té un mètode Main, és probable que estigui pensat com un programa executable en el qual pot fer servir la plantilla Aplicació de consola per crear un projecte per tal de treballar amb ell en Visual Studio .IF it has a Main method, it is likely intended es a runnable program that you can use the Console App template to create a project to work with it in Visual Studio.

Llistat de codi per a un sol archivoCode listing for a single file

Inicieu Visual Studio, obriu un projecte de consola de C # buit, seleccioneu tot el codi a l’arxiu .cs que ja és al projecte i elimínelo.Start Visual Studio, open an empty C # console project, select all the code in the .cs file that ‘s in the project already, and delete it. Després, enganxeu el contingut de el codi a l’arxiu .cs.Then, paste the contents of your code into the .cs file. A l’enganxar el codi, sobreescriga o elimini el codi que havia antes.When you paste the code, overwrite or delete the code that was there before. Canvieu el nom de l’arxiu per a que coincideixi amb el codi original.Rename the file to match the original code.

Llistats de codi per a diversos archivosCode listings for a few files

Inicieu Visual Studio , obriu un projecte de consola de C # buit, seleccioneu tot el codi a l’arxiu .cs que ja està en el projecte i elimínelo.Start Visual Studio, open an empty C # console project, select all the code in the .cs file that ‘s in the project already, and delete it. Després, enganxeu el contingut del primer arxiu de codi a l’arxiu .cs.Then, paste the contents of the first code file into the .cs file. Canvieu el nom de l’arxiu per a que coincideixi amb el codi original.Rename the file to match the original code.

Per a un segon arxiu, feu clic amb el botó dret en el node de el projecte en l’Explorador de solucions per obrir el menú contextual d’el projecte i triï Afegir > Element existent (o bé feu servir la combinació de teclat Maj + Alt + a) i seleccioneu els arxius de código.For a second file, right-click on the project node in Solution Explorer to open the drecera menu for the project, and choose Add > Existing Item (or use the key combination Maj + Alt + A), and select the code files.

Diversos arxius en discoMultiple files on disk

  1. Creeu un projecte de l’tipus adequat (utilitzeu Aplicació de consola de C # si no sabeu) .Create a new project of the appropriate type (utilitzeu C # Console App if you’r not sure).

  2. Feu clic amb el botó dret en el node d’el projecte i triï Afegir> Element existent per seleccionar els arxius i importar al proyecto.Right-click on the project node, es Add > Existing Item to select the files and import them into your project.

Inici a partir d’una carpetaStarting from a carpeta

Quan treballi amb una carpeta de molts arxius, comproveu primer si hi ha un projecte o una solución.When you’r working with a folder of many files, first see if there ‘sa project or solution. Si el programa s’ha creat amb Visual Studio, ha de buscar un arxiu de projecte o de solución.If the program was created with Visual Studio, you should find a project file or a solution file. Buscant els fitxers amb les extensions .csproj o .sln, i en l’Explorador d’arxius de Windows feu doble clic a un d’ells per obrir-los en Visual Studio.Look for files with the .csproj extensió or .sln extensió and in the Windows File Explorer , double-click on one of them to open them in Visual Studio. Vegi Inici a partir d’una solució o un projecte de Visual Studio.See Starting from a Visual Studio solution or project.

Si no té un arxiu de projecte, per exemple, si el codi s’ha desenvolupat en un altre entorn, obriu la carpeta de nivell superior amb el mètode Obre la carpeta en Visual Studio.If you do not have a project file, such as if the code was developed in another development environment, then open the top-level folder by using the Open folder method in Visual Studio. Vegi Desenvolupament de codi sense projectes o soluciones.See Develop code without projects or solutions.

Inici des d’un repositori de GitHub o Azure DevOpsStarting from a GitHub or Azure devops repo

Si el codi que vol executar està en un repositori de GitHub o d’Azure devops, pot utilitzar Visual Studio per obrir el projecte directament des del repositorio.If the code you want to run is in GitHub or in an Azure devops repo, you can use Visual Studio to open the project directly from the repo. Vegi Obertura d’un projecte des d’un repositorio.See Open a project from a repo.

Executar el programaRun the program

Per iniciar el programa, premeu la fletxa de color verd (botó Inicia) de la barra d’eines principal de Visual Studio, o bé premeu F5 o Ctrl + F5 per executar el programa.To start the program, press the green arrow (start button) on the main Visual Studio toolbar, or press F5 or Ctrl + F5 to run the program. Quan s’usa el botó Inicia, s’executa en el depurador.When you use the Start button, it runs under the debugger. Visual Studio intenta compilar el codi de el projecte i ejecutarlo.Visual Studio Attempts to build the code in your project and run it. Si l’operació es realitza correctament, perfecto.If that succeeds, great! En cas contrari, seguiu llegint per obtenir algunes idees sobre com aconseguir que es compili de forma correcta.But if not, continue reading for some idees on how to get it to build successfully.

Resolució de problemasTroubleshooting

és possible que el codi tingui errors, però si és correcte i només depèn d’altres acoblats o paquets NuGet, o bé s’ha escrit per tenir com a destinació una altra versió de .NET, és possible que el pugui corregir fàcilment. Your code might have errors, but if the code is correct, but just depends on some other assemblies or NuGet packages, or was written to target a different versio of NET, you might be able to easily fix it.

Afegir referenciasAdd references

Perquè es compili de la forma adequada, el codi ha de ser correcte i tenir les referències adequades configurades en biblioteques o altres dependencias.To build properly, the code must be correct and have the right references set up to libraries or other depèn ncies. Pot examinar les línies ondulades de color vermell i la Llista d’errors per a veure si el programa té algun error, fins i tot abans de compilar i ejecutarlo.You can look at the xarxa squiggly lines and at the Error List to see if the program has any errors , even before you compili and run it. Si veu errors relacionats amb noms sense resoldre, és probable que tingui afegir una referència o una directiva using, o les dos.If you’r seeing errors related to Unresolved names, you probably need to add a reference or a using Directive, or both . Si el codi fa referència a acoblats o paquets NuGet, haurà de afegir aquestes referències al proyecto.If the code references any assemblies or NuGet packages, necessites activar to add those references in the project.

Visual Studio intenta ajudar a identificar les referències que faltan.Visual Studio tries to help you identify missing references. Quan hi ha un nom sense resoldre, apareix una icona de bombeta al editor.When a name is Unresolved, a light bulb icon appears in the editor. Si fa clic a la bombeta, pot veure alguns suggeriments sobre com corregir el problema.If you click the light bulb, you can see some suggestions on how to fix the issue. Les correccions poden ser les següents: Fixes might be to:

  • afegir una directiva usingadd a using Directive
  • afegir una referència a un ensambladoadd a reference to an assembly, or
  • instal·lar un paquet NuGetinstall a NuGet package.

Directiva using no disponibleMissing using Directive

Per exemple, a la pantalla següent, pot optar per afegir using System; a l’inici de l’arxiu de codi per resoldre el nom sense resoldre Console: For example, in the following screen, you can choose to add using System; to the start of the code file to resoldrà the Unresolved name Console:

Captura de la bombeta per afegir una directiva using

Referència d’acoblament que faltaMissing assembly reference

Les referències de .NET poden tenir el format de acoblats o paquets NuGet..NET references can be in the form of assemblies or NuGet packages. Normalment, si troba codi font, el publicador o l’autor explicaran els acoblats que es necessiten i els paquets dels quals depèn el código.Usually, if you find source code, the publisher or Autor will explain what assemblies are required and what packages the code depends on. Per afegir manualment una referència a un projecte, feu clic amb el botó dret en el node Referències en l’Explorador de solucions, triï Afegir referència i busqui l’acoblament necesario.To add a reference to a project Manually, right-click on the References node in the Solution Explorer, choose Add Reference, and locate the required assembly.

Captura de menú Afegeix referència

Podeu cercar acoblats i afegir referències seguint les instruccions d’addició o eliminació de referències amb l’Administrador de referències.You can find assemblies and add references by following the instructions in Add or remove references by using the reference manager.

Paquet NuGet no disponibleMissing NuGet package

Si Visual Studio detecta que cal un paquet NuGet, apareix una bombeta i li ofereix l’opció d’instal·lar-lo: If Visual Studio detects a missing NuGet package, a light bulb appears and gives you the option to install it:

captura de la bombeta per instal·lar el paquet

Si això no soluciona el problema i Visual Studio no troba el paquet, intenti buscar-lo en línea.If that does not solve the issue and Visual Studio can not locate the package, try searching for it online. Vegi Instal·lació i ús d’un paquet NuGet en Visual Studio.See Install and use a NuGet package in Visual Studio.

Ús de la versió correcta de .NETUse the right versio of .NET

Com les diferents versions de .NET Framework tenen cert grau de compatibilitat amb versions anteriors, un marc de treball més recent podria executar codi escrit per a un marc anterior sense modificaciones.Because different versions of the .NET Framework have some degree of backward compatibility, a newer framework might run code written for an older framework without any Modifications. No obstant això, en ocasions és necessari tenir com a destinació un marc específico.But, sometimes you need to target a specific framework. És possible que hagi de instal · lar una revisió de .NET Framework o .NET Core, si encara no està instalada.You might need to install a specific versio of the .NET Framework or .NET Core, if it ‘s not already installed. Vegi Modificació de Visual Studio.See Modify Visual Studio.

Per canviar la plataforma de destinació, vegeu Canvi de el marc de destino.To change the target framework, see Change the target framework. Per a més informació, vegeu Solució de problemes de versió de .NET Framework de destino.For more information, see Troubleshooting .NET Framework targeting errors.

Explore l’entorn de desenvolupament de Visual Studio; per això, llegiu Li donem la benvinguda a l’IDE de Visual Studio.Explore the Visual Studio development environment by reading Welcome to the Visual Studio IDE.

Vegi tambiénSee also

Creació de la primera aplicació de C # Create your first C # app

Deixa un comentari

L'adreça electrònica no es publicarà. Els camps necessaris estan marcats amb *