CallerMemberNameAttribute Classe

Definição

Permite obter o nome de método ou propriedade do chamador do método.Allows you to obtain the method or property name of the caller to the method.

public ref class CallerMemberNameAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Parameter, Inherited=false)]
public sealed class CallerMemberNameAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Parameter, Inherited=false)>]
type CallerMemberNameAttribute = class
    inherit Attribute
Public NotInheritable Class CallerMemberNameAttribute
Inherits Attribute
Herança
CallerMemberNameAttribute
Atributos

Exemplos

O exemplo a seguir mostra como usar o CallerMemberName atributo.The following example shows how to use the CallerMemberName attribute. Em cada chamada para o TraceMessage método, as informações do chamador são substituídas como um argumento para o parâmetro opcional.On each call to the TraceMessage method, the caller information is substituted as an argument to the optional parameter.

public void DoProcessing()
{
    TraceMessage("Something happened.");
}

public void TraceMessage(string message,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    System.Diagnostics.Trace.WriteLine("message: " + message);
    System.Diagnostics.Trace.WriteLine("member name: " + memberName);
    System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);
    System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber);
}

// Sample Output:
//  message: Something happened.
//  member name: DoProcessing
//  source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs
//  source line number: 31
Private Sub DoProcessing()
    TraceMessage("Something happened.")
End Sub

Public Sub TraceMessage(message As String,
        <System.Runtime.CompilerServices.CallerMemberName> Optional memberName As String = Nothing,
        <System.Runtime.CompilerServices.CallerFilePath> Optional sourcefilePath As String = Nothing,
        <System.Runtime.CompilerServices.CallerLineNumber()> Optional sourceLineNumber As Integer = 0)

    System.Diagnostics.Trace.WriteLine("message: " & message)
    System.Diagnostics.Trace.WriteLine("member name: " & memberName)
    System.Diagnostics.Trace.WriteLine("source file path: " & sourcefilePath)
    System.Diagnostics.Trace.WriteLine("source line number: " & sourceLineNumber)
End Sub

' Sample output:
'   message: Something happened.
'   member name: DoProcessing
'   source file path: C:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoVB\CallerInfoVB\Form1.vb
'   source line number: 15

Comentários

Você aplica o CallerMemberName atributo a um parâmetro opcional que tem um valor padrão.You apply the CallerMemberName attribute to an optional parameter that has a default value. Você deve especificar um valor padrão explícito para o parâmetro opcional.You must specify an explicit default value for the optional parameter. Você não pode aplicar esse atributo a parâmetros que não são especificados como opcionais.You can't apply this attribute to parameters that aren't specified as optional.

Para obter mais informações, consulte Informações do chamador.For more information, see Caller Information.

Você pode usar o atributo CallerMemberName para evitar especificar o nome do membro como um argumento String ao método chamado.You can use the CallerMemberName attribute to avoid specifying the member name as a String argument to the called method. Ao usar essa técnica, você evita o problema de que a Refatoração de Renomeação não altera os valores de String.By using this technique, you avoid the problem that Rename Refactoring doesn't change the String values. Isso é especialmente útil para as seguintes tarefas:This is especially useful for the following tasks:

  • Usar rotinas de rastreamento e diagnóstico.Using tracing and diagnostic routines.

  • Implementando a interface INotifyPropertyChanged ao associar dados.Implementing the INotifyPropertyChanged interface when binding data. Essa interface permite que a propriedade de um objeto notifique um controle associado sobre a alteração da propriedade de modo que o controle possa exibir as informações atualizadas.This interface allows the property of an object to notify a bound control that the property has changed, so that the control can display the updated information. Sem o atributo CallerMemberName, você deve especificar o nome da propriedade como um literal.Without the CallerMemberName attribute, you must specify the property name as a literal.

O gráfico a seguir mostra os nomes de membros que são retornados quando você usa o atributo CallerMemberName.The following chart shows the member names that are returned when you use the CallerMemberName attribute.

A chamada ocorre emCall occurs within Resultado de nome de membroMember name result
Método, propriedade ou eventoMethod, property, or event O nome do método, da propriedade ou do evento em que a chamada foi originada.The name of the method, property, or event from which the call originated.
ConstrutorConstructor A cadeia de caracteres “.ctor”The string ".ctor"
Construtor estáticoStatic constructor A cadeia de caracteres “.cctor”The string ".cctor"
DestruidorDestructor A cadeia de caracteres "Finalize"The string "Finalize"
Operadores usuário ou conversões definidos pelo usuárioUser-defined operators or conversions O nome gerado para o membro, por exemplo, “op_Addition”.The generated name for the member, for example, "op_Addition".
Construtor de atributosAttribute constructor O nome do membro ao qual o atributo se aplica.The name of the member to which the attribute is applied. Se o atributo é qualquer elemento dentro de um membro (como um parâmetro, um valor de retorno, ou um parâmetro de tipo genérico), esse resultado é o nome do membro associado a esse elemento.If the attribute is any element within a member (such as a parameter, a return value, or a generic type parameter), this result is the name of the member that's associated with that element.
Nenhum membro recipiente (por exemplo, nível de assembly ou atributos aplicados a tipos)No containing member (for example, assembly-level or attributes applied to types) O valor padrão do parâmetro opcional.The default value of the optional parameter.

Construtores

CallerMemberNameAttribute()

Inicializa uma nova instância da classe CallerMemberNameAttribute.Initializes a new instance of the CallerMemberNameAttribute class.

Propriedades

TypeId

Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

(Herdado de Attribute)

Métodos

Equals(Object)

Retorna um valor que indica se essa instância é igual a um objeto especificado.Returns a value that indicates whether this instance is equal to a specified object.

(Herdado de Attribute)
GetHashCode()

Retorna o código hash para a instância.Returns the hash code for this instance.

(Herdado de Attribute)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
IsDefaultAttribute()

Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Herdado de Attribute)
Match(Object)

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Implantações explícitas de interface

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.Maps a set of names to a corresponding set of dispatch identifiers.

(Herdado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.Retrieves the type information for an object, which can be used to get the type information for an interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Herdado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.Provides access to properties and methods exposed by an object.

(Herdado de Attribute)

Aplica-se a

Confira também