次の方法で共有


NameOf 演算子 - Visual Basic

NameOf演算子は、変数、型、またはメンバーの名前を文字列定数として取得します。

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

前の例に示すように、型と名前空間の場合、通常、生成された名前は 完全修飾されません。

NameOf演算子はコンパイル時に評価され、実行時には影響しません。

NameOf演算子を使用して、引数チェック コードをより保守しやすいものにすることができます。

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

NameOf演算子は、Visual Basic 14 以降で使用できます。

こちらも参照ください