Debug.Assert Método
Definição
Verifica uma condição; se ela for false, gera mensagens e exibe uma caixa de mensagem que mostra a pilha de chamadas.Checks for a condition; if the condition is false, outputs messages and displays a message box that shows the call stack.
Sobrecargas
| Assert(Boolean) |
Verifica uma condição; se a condição for |
| Assert(Boolean, String) |
Verifica uma condição, se a condição for |
| Assert(Boolean, String, String) |
Verifica uma condição. Se a condição for |
| Assert(Boolean, String, String, Object[]) |
Verifica uma condição, se a condição for |
Assert(Boolean)
Verifica uma condição; se a condição for false, exibirá uma caixa de mensagem que mostra a pilha de chamadas.Checks for a condition; if the condition is false, displays a message box that shows the call stack.
public:
static void Assert(bool condition);
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert (bool condition);
[<System.Diagnostics.Conditional("DEBUG")>]
static member Assert : bool -> unit
Public Shared Sub Assert (condition As Boolean)
Parâmetros
- condition
- Boolean
A expressão condicional a ser avaliada.The conditional expression to evaluate. Se a condição for true, uma mensagem de falha não será enviada e a caixa de mensagem não será exibida.If the condition is true, a failure message is not sent and the message box is not displayed.
- Atributos
Exemplos
O exemplo a seguir cria um índice para uma matriz, executa alguma ação para definir o valor do índice e, em seguida, chama Assert para confirmar que o valor do índice é válido.The following example creates an index for an array, performs some action to set the value of the index, and then calls Assert to confirm that the index value is valid. Se não for válido, Assert o produzirá a pilha de chamadas.If it is not valid, Assert outputs the call stack.
// Create a local value.
int index;
// Perform some action that sets the local value.
index = -40;
// Test that the local value is valid.
#if defined(DEBUG)
Debug::Assert( index > -1 );
#endif
// Create an index for an array.
int index;
// Perform some action that sets the index.
index = -40;
// Test that the index value is valid.
Debug.Assert(index > -1);
' Create an index for an array.
Dim index As Integer
' Perform some action that sets the index.
index = -40
' Test that the index value is valid.
Debug.Assert((index > - 1))
Comentários
Por padrão, o Debug.Assert método funciona apenas em compilações de depuração.By default, the Debug.Assert method works only in debug builds. Use o Trace.Assert método se você quiser fazer asserções em compilações de versão.Use the Trace.Assert method if you want to do assertions in release builds. Para obter mais informações, confira Asserções em código gerenciado.For more information, see Assertions in Managed Code.
Importante
Os Assert métodos não estão disponíveis para aplicativos da Windows Store.The Assert methods are not available for Windows Store apps.
Normalmente, o Assert(Boolean) método é usado para identificar erros lógicos durante o desenvolvimento do programa.Typically, the Assert(Boolean) method is used to identify logic errors during program development. Assert avalia a condição.Assert evaluates the condition. Se o resultado for false , ele enviará uma mensagem de falha à Listeners coleção.If the result is false, it sends a failure message to the Listeners collection. Você pode personalizar esse comportamento adicionando um TraceListener ou removendo um da Listeners coleção.You can customize this behavior by adding a TraceListener to, or removing one from, the Listeners collection.
Quando o aplicativo é executado no modo de interface do usuário, ele exibe uma caixa de mensagem que mostra a pilha de chamadas com números de arquivo e de linha.When the application runs in user interface mode, it displays a message box that shows the call stack with file and line numbers. A caixa de mensagem contém três botões: anular, repetir e ignorar.The message box contains three buttons: Abort, Retry, and Ignore. Clicar no botão anular encerra o aplicativo.Clicking the Abort button terminates the application. Clicar em repetir enviará a você o código no depurador se seu aplicativo estiver em execução em um depurador ou se o for aberto para abrir um depurador, se não for.Clicking Retry sends you to the code in the debugger if your application is running in a debugger, or offers to open a debugger if it is not. Clicar em ignorar continua com a próxima instrução no código.Clicking Ignore continues with the next instruction in the code.
Observação
Os aplicativos da loja do Windows 8. x não dão suporte a caixas de diálogo modais e, portanto, se comportam da mesma forma no modo de interface do usuário e no modo de interface não do usuário.Windows 8.x Store apps do not support modal dialog boxes, so they behave the same in user interface mode and non-user interface mode. A mensagem é gravada nos ouvintes de rastreamento ativos no modo de depuração ou nenhuma mensagem é gravada no modo de versão.The message is written to the active trace listeners in debugging mode, or no message is written in release mode.
Observação
A exibição da caixa de mensagem depende da presença do DefaultTraceListener .The display of the message box depends on the presence of the DefaultTraceListener. Se o DefaultTraceListener não estiver na Listeners coleção, a caixa de mensagem não será exibida.If the DefaultTraceListener is not in the Listeners collection, the message box is not displayed. O DefaultTraceListener pode ser removido por < > Clear, < Remove > ou chamando o Clear método na Listeners Propriedade ( System.Diagnostics.Trace.Listeners.Clear() ).The DefaultTraceListener can be removed by the <clear>, the <remove>, or by calling the Clear method on the Listeners property (System.Diagnostics.Trace.Listeners.Clear()).
Você pode alterar o comportamento do DefaultTraceListener no arquivo de configuração que corresponde ao nome do seu aplicativo.You can change the behavior of the DefaultTraceListener in the configuration file that corresponds to the name of your application. Nesse arquivo, você pode habilitar e desabilitar a caixa de mensagem Assert ou definir a DefaultTraceListener.LogFileName propriedade.In this file, you can enable and disable the assert message box or set the DefaultTraceListener.LogFileName property. O arquivo de configuração deve ser formatado da seguinte maneira:The configuration file should be formatted as follows:
<configuration>
<system.diagnostics>
<assert assertuienabled="true" logfilename="c:\\myFile.log" />
</system.diagnostics>
</configuration>
Confira também
- Debug
- Trace
- BooleanSwitch
- TraceSwitch
- TraceListener
- DefaultTraceListener
- ConsoleTraceListener
- ConditionalAttribute
Aplica-se a
Assert(Boolean, String)
Verifica uma condição, se a condição for false, gerará uma mensagem especificada e exibirá uma caixa de mensagem que mostra a pilha de chamadas.Checks for a condition; if the condition is false, outputs a specified message and displays a message box that shows the call stack.
public:
static void Assert(bool condition, System::String ^ message);
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert (bool condition, string message);
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert (bool condition, string? message);
[<System.Diagnostics.Conditional("DEBUG")>]
static member Assert : bool * string -> unit
Public Shared Sub Assert (condition As Boolean, message As String)
Parâmetros
- condition
- Boolean
A expressão condicional a ser avaliada.The conditional expression to evaluate. Se a condição for true, a mensagem especificada não será enviada e a caixa de mensagem não será exibida.If the condition is true, the specified message is not sent and the message box is not displayed.
- message
- String
A mensagem a ser enviada para a coleção Listeners.The message to send to the Listeners collection.
- Atributos
Exemplos
O exemplo a seguir verifica se o type parâmetro é válido.The following example checks whether the type parameter is valid. Se type for null , Assert gera uma mensagem.If type is null, Assert outputs a message.
void MyMethod( Object^ obj, Type^ type )
{
#if defined(DEBUG)
Debug::Assert( type != nullptr, "Type paramater is null" );
#endif
}
public static void MyMethod(Type type, Type baseType) {
Debug.Assert(type != null, "Type parameter is null");
// Perform some processing.
}
Public Shared Sub MyMethod(type As Type, baseType As Type)
Debug.Assert(Not (type Is Nothing), "Type parameter is null")
End Sub
Comentários
Por padrão, o Debug.Assert método funciona apenas em compilações de depuração.By default, the Debug.Assert method works only in debug builds. Use o Trace.Assert método se você quiser fazer asserções em compilações de versão.Use the Trace.Assert method if you want to do assertions in release builds. Para obter mais informações, confira Asserções em código gerenciado.For more information, see Assertions in Managed Code.
Normalmente, o Assert método é usado para identificar erros lógicos durante o desenvolvimento do programa.Typically, the Assert method is used to identify logic errors during program development. Assert avalia a condição.Assert evaluates the condition. Se o resultado for false , ele enviará a mensagem de diagnóstico especificada para a Listeners coleção.If the result is false, it sends the specified diagnostic message to the Listeners collection. Você pode personalizar esse comportamento adicionando um TraceListener ou removendo um da Listeners coleção.You can customize this behavior by adding a TraceListener to, or removing one from, the Listeners collection.
Quando o aplicativo é executado no modo de interface do usuário, ele exibe uma caixa de mensagem que mostra a pilha de chamadas com números de arquivo e de linha.When the application runs in user interface mode, it displays a message box that shows the call stack with file and line numbers. A caixa de mensagem contém três botões: anular, repetir e ignorar.The message box contains three buttons: Abort, Retry, and Ignore. Clicar no botão anular encerra o aplicativo.Clicking the Abort button terminates the application. Clicar em repetir enviará a você o código no depurador se seu aplicativo estiver em execução em um depurador ou se o for aberto para abrir um depurador, se não for.Clicking Retry sends you to the code in the debugger if your application is running in a debugger, or offers to open a debugger if it is not. Clicar em ignorar continua com a próxima instrução no código.Clicking Ignore continues with the next instruction in the code.
Observação
A exibição da caixa de mensagem depende da presença do DefaultTraceListener .The display of the message box depends on the presence of the DefaultTraceListener. Se o DefaultTraceListener não estiver na Listeners coleção, a caixa de mensagem não será exibida.If the DefaultTraceListener is not in the Listeners collection, the message box is not displayed. O DefaultTraceListener pode ser removido por < > Clear, < Remove > ou chamando o Clear método na Listeners Propriedade ( System.Diagnostics.Trace.Listeners.Clear() ).The DefaultTraceListener can be removed by the <clear>, the <remove>, or by calling the Clear method on the Listeners property (System.Diagnostics.Trace.Listeners.Clear()).
Você pode alterar o comportamento do DefaultTraceListener no arquivo de configuração que corresponde ao nome do seu aplicativo.You can change the behavior of the DefaultTraceListener in the configuration file that corresponds to the name of your application. Nesse arquivo, você pode habilitar e desabilitar a caixa de mensagem Assert ou definir a DefaultTraceListener.LogFileName propriedade.In this file, you can enable and disable the assert message box or set the DefaultTraceListener.LogFileName property. O arquivo de configuração deve ser formatado da seguinte maneira:The configuration file should be formatted as follows:
<configuration>
<system.diagnostics>
<assert assertuienabled="true" logfilename="c:\\myFile.log" />
</system.diagnostics>
</configuration>
Confira também
- Debug
- Trace
- BooleanSwitch
- TraceSwitch
- TraceListener
- DefaultTraceListener
- ConsoleTraceListener
- ConditionalAttribute
Aplica-se a
Assert(Boolean, String, String)
Verifica uma condição. Se a condição for false, gerará duas mensagens especificadas e exibe uma caixa de mensagem que mostra a pilha de chamadas.Checks for a condition; if the condition is false, outputs two specified messages and displays a message box that shows the call stack.
public:
static void Assert(bool condition, System::String ^ message, System::String ^ detailMessage);
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert (bool condition, string message, string detailMessage);
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert (bool condition, string? message, string? detailMessage);
[<System.Diagnostics.Conditional("DEBUG")>]
static member Assert : bool * string * string -> unit
static member Assert : bool * string * string -> unit
Public Shared Sub Assert (condition As Boolean, message As String, detailMessage As String)
Parâmetros
- condition
- Boolean
A expressão condicional a ser avaliada.The conditional expression to evaluate. Se a condição for true, as mensagens especificadas não serão enviadas e a caixa de mensagem não será exibida.If the condition is true, the specified messages are not sent and the message box is not displayed.
- message
- String
A mensagem a ser enviada para a coleção Listeners.The message to send to the Listeners collection.
- detailMessage
- String
A mensagem detalhada a ser enviada para a coleção Listeners.The detailed message to send to the Listeners collection.
- Atributos
Exemplos
O exemplo a seguir verifica se o type parâmetro é válido.The following example checks whether the type parameter is valid. Se type for null , Assert gera duas mensagens.If type is null, Assert outputs two messages.
void MyMethod( Object^ obj, Type^ type )
{
#if defined(DEBUG)
Debug::Assert( type != nullptr, "Type paramater is null", "Can't get object for null type" );
#endif
}
public static void MyMethod(Type type, Type baseType) {
Debug.Assert(type != null, "Type parameter is null",
"Can't get object for null type");
// Perform some processing.
}
Public Shared Sub MyMethod(type As Type, baseType As Type)
Debug.Assert( Not (type Is Nothing), "Type parameter is null", "Can't get object for null type")
' Perform some processing.
End Sub
Comentários
Por padrão, o Debug.Assert método funciona apenas em compilações de depuração.By default, the Debug.Assert method works only in debug builds. Use o Trace.Assert método se você quiser fazer asserções em compilações de versão.Use the Trace.Assert method if you want to do assertions in release builds. Para obter mais informações, confira Asserções em código gerenciado.For more information, see Assertions in Managed Code.
Normalmente, o Assert(Boolean, String, String) método é usado para identificar erros lógicos durante o desenvolvimento do programa.Typically, the Assert(Boolean, String, String) method is used to identify logic errors during program development. Assert avalia a condição.Assert evaluates the condition. Se o resultado for false , ele enviará a mensagem de diagnóstico especificada e a mensagem detalhada para a Listeners coleção.If the result is false, it sends the specified diagnostic message and detailed message to the Listeners collection. Você pode personalizar esse comportamento adicionando um TraceListener ou removendo um da Listeners coleção.You can customize this behavior by adding a TraceListener to, or removing one from, the Listeners collection.
Quando o aplicativo é executado no modo de interface do usuário, ele exibe uma caixa de mensagem que mostra a pilha de chamadas com números de arquivo e de linha.When the application runs in user interface mode, it displays a message box that shows the call stack with file and line numbers. A caixa de mensagem contém três botões: anular, repetir e ignorar.The message box contains three buttons: Abort, Retry, and Ignore. Clicar no botão anular encerra o aplicativo.Clicking the Abort button terminates the application. Clicar em repetir enviará a você o código no depurador se seu aplicativo estiver em execução em um depurador ou se o for aberto para abrir um depurador, se não for.Clicking Retry sends you to the code in the debugger if your application is running in a debugger, or offers to open a debugger if it is not. Clicar em ignorar continua com a próxima instrução no código.Clicking Ignore continues with the next instruction in the code.
Observação
A exibição da caixa de mensagem depende da presença do DefaultTraceListener .The display of the message box depends on the presence of the DefaultTraceListener. Se o DefaultTraceListener não estiver na Listeners coleção, a caixa de mensagem não será exibida.If the DefaultTraceListener is not in the Listeners collection, the message box is not displayed. O DefaultTraceListener pode ser removido por < > Clear, < Remove > ou chamando o Clear método na Listeners Propriedade ( System.Diagnostics.Trace.Listeners.Clear() ).The DefaultTraceListener can be removed by the <clear>, the <remove>, or by calling the Clear method on the Listeners property (System.Diagnostics.Trace.Listeners.Clear()).
Você pode alterar o comportamento do DefaultTraceListener no arquivo de configuração que corresponde ao nome do seu aplicativo.You can change the behavior of the DefaultTraceListener in the configuration file that corresponds to the name of your application. Nesse arquivo, você pode habilitar e desabilitar a caixa de mensagem Assert ou definir a DefaultTraceListener.LogFileName propriedade.In this file, you can enable and disable the assert message box or set the DefaultTraceListener.LogFileName property. O arquivo de configuração deve ser formatado da seguinte maneira:The configuration file should be formatted as follows:
<configuration>
<system.diagnostics>
<assert assertuienabled="true" logfilename="c:\\myFile.log" />
</system.diagnostics>
</configuration>
Confira também
- Debug
- Trace
- BooleanSwitch
- TraceSwitch
- TraceListener
- DefaultTraceListener
- ConsoleTraceListener
- ConditionalAttribute
Aplica-se a
Assert(Boolean, String, String, Object[])
Verifica uma condição, se a condição for false, gerará duas mensagens (simples e formatadas) e exibirá uma caixa de mensagem que mostra a pilha de chamadas.Checks for a condition; if the condition is false, outputs two messages (simple and formatted) and displays a message box that shows the call stack.
public:
static void Assert(bool condition, System::String ^ message, System::String ^ detailMessageFormat, ... cli::array <System::Object ^> ^ args);
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert (bool condition, string message, string detailMessageFormat, params object[] args);
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert (bool condition, string? message, string detailMessageFormat, params object?[] args);
[<System.Diagnostics.Conditional("DEBUG")>]
static member Assert : bool * string * string * obj[] -> unit
static member Assert : bool * string * string * obj[] -> unit
Public Shared Sub Assert (condition As Boolean, message As String, detailMessageFormat As String, ParamArray args As Object())
Parâmetros
- condition
- Boolean
A expressão condicional a ser avaliada.The conditional expression to evaluate. Se a condição for true, as mensagens especificadas não serão enviadas e a caixa de mensagem não será exibida.If the condition is true, the specified messages are not sent and the message box is not displayed.
- message
- String
A mensagem a ser enviada para a coleção Listeners.The message to send to the Listeners collection.
- detailMessageFormat
- String
A cadeia de caracteres de formato de composição para a coleção Listeners.The composite format string to send to the Listeners collection. Essa mensagem contém texto misturado com zero ou mais itens de formato, que correspondem aos objetos na matriz args.This message contains text intermixed with zero or more format items, which correspond to objects in the args array.
- args
- Object[]
Uma matriz de objetos que contém zero ou mais objetos a serem formatados.An object array that contains zero or more objects to format.
- Atributos
Comentários
Esse método usa o recurso de formatação composta do .net para converter o valor de um objeto em sua representação de texto e inserir essa representação em uma cadeia de caracteres.This method uses the .NET composite formatting feature to convert the value of an object to its text representation and embed that representation in a string. A cadeia de caracteres resultante é enviada para a Listeners coleção.The resulting string is sent to the Listeners collection.
Por padrão, o Debug.Assert método funciona apenas em compilações de depuração.By default, the Debug.Assert method works only in debug builds. Use o Trace.Assert método se você quiser fazer asserções em compilações de versão.Use the Trace.Assert method if you want to do assertions in release builds. Para obter mais informações, confira Asserções em código gerenciado.For more information, see Assertions in Managed Code.
Normalmente, o Assert(Boolean, String, String, Object[]) método é usado para identificar erros lógicos durante o desenvolvimento do programa.Typically, the Assert(Boolean, String, String, Object[]) method is used to identify logic errors during program development. Assert avalia a condição.Assert evaluates the condition. Se o resultado for false , o String.Format(String, Object[]) método será chamado e a detailMessageFormat cadeia de caracteres e a args matriz serão passados como parâmetros.If the result is false, The String.Format(String, Object[]) method is called and the detailMessageFormat string and args array are passed in as parameters. Assert(Boolean, String, String, Object[]) em seguida, o envia a mensagem de texto especificada e a mensagem de texto formatado para a Listeners coleção.Assert(Boolean, String, String, Object[]) then sends the specified text message and the formatted text message to the Listeners collection. Você pode personalizar esse comportamento adicionando um TraceListener ou removendo um da Listeners coleção.You can customize this behavior by adding a TraceListener to, or removing one from, the Listeners collection.
Quando o aplicativo é executado no modo de interface do usuário, ele exibe uma caixa de mensagem que mostra a pilha de chamadas com números de arquivo e de linha.When the application runs in user interface mode, it displays a message box that shows the call stack with file and line numbers. A caixa de mensagem contém três botões: anular, repetir e ignorar.The message box contains three buttons: Abort, Retry, and Ignore. Clicar no botão anular encerra o aplicativo.Clicking the Abort button terminates the application. Clicar em repetir enviará a você o código no depurador se seu aplicativo estiver em execução em um depurador ou se o for aberto para abrir um depurador, se não for.Clicking Retry sends you to the code in the debugger if your application is running in a debugger, or offers to open a debugger if it is not. Clicar em ignorar continua com a próxima instrução no código.Clicking Ignore continues with the next instruction in the code.
Observação
A exibição da caixa de mensagem depende da presença do DefaultTraceListener .The display of the message box is dependent on the presence of the DefaultTraceListener. Se o DefaultTraceListener não estiver na Listeners coleção, a caixa de mensagem não será exibida.If the DefaultTraceListener is not in the Listeners collection, the message box is not displayed. O DefaultTraceListener pode ser removido por < > Clear, < Remove > ou chamando o Clear método na Listeners Propriedade ( System.Diagnostics.Trace.Listeners.Clear() ).The DefaultTraceListener can be removed by the <clear>, the <remove>, or by calling the Clear method on the Listeners property (System.Diagnostics.Trace.Listeners.Clear()).
Você pode alterar o comportamento do DefaultTraceListener no arquivo de configuração que corresponde ao nome do seu aplicativo.You can change the behavior of the DefaultTraceListener in the configuration file that corresponds to the name of your application. Nesse arquivo, você pode habilitar e desabilitar a caixa de mensagem Assert ou definir a DefaultTraceListener.LogFileName propriedade.In this file, you can enable and disable the assert message box or set the DefaultTraceListener.LogFileName property. O arquivo de configuração deve ser formatado da seguinte maneira:The configuration file should be formatted as follows:
<configuration>
<system.diagnostics>
<assert assertuienabled="true" logfilename="c:\\myFile.log" />
</system.diagnostics>
</configuration>