CompilerError Classe
Definição
Representa um erro ou aviso de compilador.Represents a compiler error or warning.
public ref class CompilerError
public class CompilerError
[System.Serializable]
public class CompilerError
type CompilerError = class
[<System.Serializable>]
type CompilerError = class
Public Class CompilerError
- Herança
-
CompilerError
- Derivado
- Atributos
Exemplos
O exemplo a seguir compila um grafo do programa CodeDOM e fornece um exemplo de como acessar programaticamente os dados do CompilerError.The following example compiles a CodeDOM program graph and provides an example of how to programmatically access CompilerError data.
#using <System.dll>
using namespace System;
using namespace System::CodeDom;
using namespace System::CodeDom::Compiler;
using namespace Microsoft::CSharp;
CodeCompileUnit^ GetCompileUnit()
{
// Create a compile unit to contain a CodeDOM graph.
CodeCompileUnit^ cu = gcnew CodeCompileUnit;
// Create a namespace named TestSpace.
CodeNamespace^ cn = gcnew CodeNamespace( "TestSpace" );
// Declare a new type named TestClass.
CodeTypeDeclaration^ cd = gcnew CodeTypeDeclaration( "TestClass" );
// Declare a new member string field named TestField.
CodeMemberField^ cmf = gcnew CodeMemberField( "System.String","TestField" );
// Add the field to the type.
cd->Members->Add( cmf );
// Declare a new member method named TestMethod.
CodeMemberMethod^ cm = gcnew CodeMemberMethod;
cm->Name = "TestMethod";
// Declare a string variable named TestVariable.
CodeVariableDeclarationStatement^ cvd = gcnew CodeVariableDeclarationStatement( "System.String1","TestVariable" );
cm->Statements->Add( cvd );
// Cast the TestField reference expression to string and assign it to the TestVariable.
CodeAssignStatement^ ca = gcnew CodeAssignStatement( gcnew CodeVariableReferenceExpression( "TestVariable" ),gcnew CodeCastExpression( "System.String2",gcnew CodeFieldReferenceExpression( gcnew CodeThisReferenceExpression,"TestField" ) ) );
// This code can be used to generate the following code in C#:
// TestVariable = ((string)(this.TestField));
cm->Statements->Add( ca );
// Add the TestMethod member to the TestClass type.
cd->Members->Add( cm );
// Add the TestClass type to the namespace.
cn->Types->Add( cd );
// Add the TestSpace namespace to the compile unit.
cu->Namespaces->Add( cn );
return cu;
}
int main()
{
// Output some program information using Console.WriteLine.
Console::WriteLine( "This program compiles a CodeDOM program that incorrectly declares multiple data" );
Console::WriteLine( "types to demonstrate handling compiler errors programmatically." );
Console::WriteLine( "" );
// Compile the CodeCompileUnit retrieved from the GetCompileUnit() method.
//CSharpCodeProvider ^ provider = gcnew Microsoft::CSharp::CSharpCodeProvider;
CodeDomProvider ^ provider = CodeDomProvider::CreateProvider("CSharp");
// Initialize a CompilerParameters with the options for compilation.
array<String^>^assemblies = {"System.dll"};
CompilerParameters^ options = gcnew CompilerParameters( assemblies,"output.exe" );
// Compile the CodeDOM graph and store the results in a CompilerResults.
CompilerResults^ results = provider->CompileAssemblyFromDom( options, GetCompileUnit() );
// Compilation produces errors. Print out each error.
Console::WriteLine( "Listing errors from compilation: " );
Console::WriteLine( "" );
for ( int i = 0; i < results->Errors->Count; i++ )
Console::WriteLine( results->Errors[ i ] );
}
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
namespace CompilerError_Example
{
public class Class1
{
[STAThread]
static void Main(string[] args)
{
// Output some program information using Console.WriteLine.
Console.WriteLine("This program compiles a CodeDOM program that incorrectly declares multiple data");
Console.WriteLine("types to demonstrate handling compiler errors programmatically.");
Console.WriteLine("");
// Compile the CodeCompileUnit retrieved from the GetCompileUnit() method.
CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
// Initialize a CompilerParameters with the options for compilation.
string[] assemblies = new String[] {"System.dll"};
CompilerParameters options = new CompilerParameters( assemblies, "output.exe");
// Compile the CodeDOM graph and store the results in a CompilerResults.
CompilerResults results = provider.CompileAssemblyFromDom(options, GetCompileUnit());
// Compilation produces errors. Print out each error.
Console.WriteLine("Listing errors from compilation: ");
Console.WriteLine("");
for( int i=0; i<results.Errors.Count; i++)
Console.WriteLine(results.Errors[i].ToString());
}
public static CodeCompileUnit GetCompileUnit()
{
// Create a compile unit to contain a CodeDOM graph.
CodeCompileUnit cu = new CodeCompileUnit();
// Create a namespace named TestSpace.
CodeNamespace cn = new CodeNamespace("TestSpace");
// Declare a new type named TestClass.
CodeTypeDeclaration cd = new CodeTypeDeclaration("TestClass");
// Declare a new member string field named TestField.
CodeMemberField cmf = new CodeMemberField("System.String", "TestField");
// Add the field to the type.
cd.Members.Add(cmf);
// Declare a new member method named TestMethod.
CodeMemberMethod cm = new CodeMemberMethod();
cm.Name = "TestMethod";
// Declare a string variable named TestVariable.
CodeVariableDeclarationStatement cvd = new CodeVariableDeclarationStatement("System.String1", "TestVariable");
cm.Statements.Add(cvd);
// Cast the TestField reference expression to string and assign it to the TestVariable.
CodeAssignStatement ca = new CodeAssignStatement(new CodeVariableReferenceExpression("TestVariable"),
new CodeCastExpression("System.String2", new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "TestField")));
// This code can be used to generate the following code in C#:
// TestVariable = ((string)(this.TestField));
cm.Statements.Add(ca);
// Add the TestMethod member to the TestClass type.
cd.Members.Add(cm);
// Add the TestClass type to the namespace.
cn.Types.Add(cd);
// Add the TestSpace namespace to the compile unit.
cu.Namespaces.Add(cn);
return cu;
}
}
}
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports Microsoft.CSharp
Namespace CompilerError_Example
_
Class Class1
Shared Sub Main()
' Output some program information using Console.WriteLine.
Console.WriteLine("This program compiles a CodeDOM program that incorrectly declares multiple data")
Console.WriteLine("types to demonstrate handling compiler errors programatically.")
Console.WriteLine("")
' Compile the CodeCompileUnit retrieved from the GetCompileUnit() method.
Dim provider As CodeDomProvider
provider = CodeDomProvider.CreateProvider("CSharp")
' Initialize a CompilerParameters with the options for compilation.
Dim assemblies() As String = New [String]() {"System.dll"}
Dim options As New CompilerParameters(assemblies, "output.exe")
' Compile the CodeDOM graph and store the results in a CompilerResults.
Dim results As CompilerResults = provider.CompileAssemblyFromDom(options, GetCompileUnit())
' Compilation produces errors. Print out each error.
Console.WriteLine("Listing errors from compilation: ")
Console.WriteLine("")
Dim i As Integer
For i = 0 To results.Errors.Count - 1
Console.WriteLine(results.Errors(i).ToString())
Next i
End Sub
Public Shared Function GetCompileUnit() As CodeCompileUnit
' Create a compile unit to contain a CodeDOM graph.
Dim cu As New CodeCompileUnit()
' Create a namespace named TestSpace.
Dim cn As New CodeNamespace("TestSpace")
' Declare a new type named TestClass.
Dim cd As New CodeTypeDeclaration("TestClass")
' Declare a new member string field named TestField.
Dim cmf As New CodeMemberField("System.String", "TestField")
' Add the field to the type.
cd.Members.Add(cmf)
' Declare a new member method named TestMethod.
Dim cm As New CodeMemberMethod()
cm.Name = "TestMethod"
' Declare a string variable named TestVariable.
Dim cvd As New CodeVariableDeclarationStatement("System.String1", "TestVariable")
cm.Statements.Add(cvd)
' Cast the TestField reference expression to string and assign it to the TestVariable.
Dim ca As New CodeAssignStatement(New CodeVariableReferenceExpression("TestVariable"), New CodeCastExpression("System.String2", New CodeFieldReferenceExpression(New CodeThisReferenceExpression(), "TestField")))
' This code can be used to generate the following code in C#:
' TestVariable = ((string)(this.TestField));
cm.Statements.Add(ca)
' Add the TestMethod member to the TestClass type.
cd.Members.Add(cm)
' Add the TestClass type to the namespace.
cn.Types.Add(cd)
' Add the TestSpace namespace to the compile unit.
cu.Namespaces.Add(cn)
Return cu
End Function
End Class
End Namespace
Comentários
CompilerError representa um erro do compilador ou um aviso que foi retornado pelo compilador.CompilerError represents a compiler error or a warning that has been returned by the compiler.
Observação
Essa classe contém uma demanda de herança no nível de classe que se aplica a todos os membros.This class contains an inheritance demand at the class level that applies to all members. Um SecurityException é gerado quando a classe derivada não tem permissão de confiança total.A SecurityException is thrown when the derived class does not have full-trust permission. Para obter detalhes sobre as demandas de herança, consulte demandas de herança.For details about inheritance demands, see Inheritance Demands.
Construtores
| CompilerError() |
Inicializa uma nova instância da classe CompilerError.Initializes a new instance of the CompilerError class. |
| CompilerError(String, Int32, Int32, String, String) |
Inicializa uma nova instância da classe CompilerError usando o nome do arquivo, coluna, número do erro e texto do erro especificados.Initializes a new instance of the CompilerError class using the specified file name, line, column, error number, and error text. |
Propriedades
| Column |
Obtém ou define o número da coluna em que a origem do erro ocorre.Gets or sets the column number where the source of the error occurs. |
| ErrorNumber |
Obtém ou define o número do erro.Gets or sets the error number. |
| ErrorText |
Obtém ou define o texto da mensagem de erro.Gets or sets the text of the error message. |
| FileName |
Obtém ou define o nome do arquivo de origem que contém o código que causou o erro.Gets or sets the file name of the source file that contains the code which caused the error. |
| IsWarning |
Obtém ou define um valor que indica se o erro é um aviso.Gets or sets a value that indicates whether the error is a warning. |
| Line |
Obtém ou define o número de linha em que a origem do erro ocorre.Gets or sets the line number where the source of the error occurs. |
Métodos
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| ToString() |
Fornece uma implementação do método ToString() do objeto.Provides an implementation of Object's ToString() method. |