Operador NameOf: Visual Basic
El operador NameOf
obtiene el nombre de una variable, un tipo o un miembro como la constante de cadena:
Console.WriteLine(NameOf(System.Collections.Generic)) ' output: Generic
Console.WriteLine(NameOf(List(Of Integer))) ' output: List
Console.WriteLine(NameOf(List(Of Integer).Count)) ' output: Count
Console.WriteLine(NameOf(List(Of Integer).Add)) ' output: Add
Dim numbers As New List(Of Integer) From { 1, 2, 3 }
Console.WriteLine(NameOf(numbers)) ' output: numbers
Console.WriteLine(NameOf(numbers.Count)) ' output: Count
Console.WriteLine(NameOf(numbers.Add)) ' output: Add
Como se muestra en el ejemplo anterior, en el caso de un tipo y un espacio de nombres, el nombre generado por lo general no está completo.
El operador NameOf
se evalúa en tiempo de compilación y no tiene efecto en tiempo de ejecución.
Puede usar el operador NameOf
para hacer que el código de comprobación de argumentos sea más fácil de mantener:
Private _name As String
Public Property Name As String
Get
Return _name
End Get
Set
If value Is Nothing Then
Throw New ArgumentNullException(NameOf(value), $"{NameOf(name)} cannot be null.")
End If
End Set
End Property
El operador NameOf
está disponible en Visual Basic 14 y versiones posteriores.
Vea también
Comentarios
https://aka.ms/ContentUserFeedback.
Próximamente: A lo largo de 2024 iremos eliminando gradualmente las Cuestiones de GitHub como mecanismo de retroalimentación para el contenido y lo sustituiremos por un nuevo sistema de retroalimentación. Para más información, consulta:Enviar y ver comentarios de