Visual Basic .NETNameOf运算符

示例

该NameOf操作符解析命名空间,类型,变量和成员名称在编译时用绳子等效替换它们。

用例之一:

Sub MySub(variable As String)
    If variable Is Nothing Then Throw New ArgumentNullException("variable")
End Sub

旧的语法会带来重命名变量并使硬编码的字符串保持错误值的风险。

Sub MySub(variable As String)
    If variable Is Nothing Then Throw New ArgumentNullException(NameOf(variable))
End Sub

使用NameOf,仅重命名变量将引发编译器错误。这也将使重命名工具可以一次完成重命名。

该NameOf操作仅使用括号中的参考的最后一个组件。在NameOf运算符中处理诸如名称空间之类的内容时,这一点很重要。

Imports System

Module Module1
    Sub WriteIO()
        Console.WriteLine(NameOf(IO)) 'displays "IO"
        Console.WriteLine(NameOf(System.IO)) 'displays "IO"
    End Sub
End Module

运算符还使用键入的引用的名称,而无需解决任何更改导入的名称。例如:

Imports OldList = System.Collections.ArrayList

Module Module1
    Sub WriteList()
        Console.WriteLine(NameOf(OldList)) 'displays "OldList"
        Console.WriteLine(NameOf(System.Collections.ArrayList)) 'displays "ArrayList"
    End Sub
End Module