vb.net - 使用类型别名来定义类型别名

标签 vb.net

作为DRY(Don't Repeat Yourself)的狂热信徒,我只写了这段代码:

Imports SimpleDict = System.Collections.Generic.Dictionary(Of String, String)
Imports ListOfSimpleDicts = System.Collections.Generic.List(Of SimpleDict)
Imports DictOfSimpleDicts = System.Collections.Generic.Dictionary(Of String, SimpleDict)

我立即收到错误消息,“类型‘SimpleDict’未定义。”在最后两行。有没有办法避免在我的类型别名中重复我自己?

[附录] 24 小时后,我不得不将 SimpleDict 更改为别名 Dictionary(Of String, HashSet)。好消息是,由于我使用的是别名,我的更改会传播到我使用过的所有地方,但不幸的是,我仍然需要自己更改其他两行。

最佳答案

From the VB specification

Imports statements make names available in a source file, but do not declare anything in the global namespace's declaration space. The scope of the names imported by an Imports statement extends over the namespace member declarations contained in the source file. The scope of an Imports statement specifically does not include other Imports statements, nor does it include other source files. Imports statements may not refer to one another.

In this example, the last Imports statement is in error because it is not affected by the first import alias.

Imports R1 = N1 ' OK.
Imports R2 = N1.N2 ' OK.
Imports R3 = R1.N2 ' Error: Can't refer to R1.

我不确定你可以做什么。我唯一能想到的是将 SimpleDict 定义为 System.Collections.Generic.Dictionary(Of String, String) 的类,不确定这是否适合您因为你必须创建一个类。

Imports ListOfSimpleDicts = System.Collections.Generic.List(Of RootNamespace.SimpleDict)
Imports DictOfSimpleDicts = System.Collections.Generic.Dictionary(Of String, RootNamespace.SimpleDict)

Public Class SimpleDict
    Inherits System.Collections.Generic.Dictionary(Of String, String)
End Class

关于vb.net - 使用类型别名来定义类型别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45735987/

相关文章:

.net - 我可以使用 VB.NET 覆盖类中声明的变量吗?

c# - 为运行时或编译时引用所有必需的程序集?

ASP.NET 导出到 Excel - 锁定单元格

vb.net - 如何返回与登录用户当前 Outlook 配置文件关联的主电子邮件地址?

c# - ModalPopUpExtender 内的 Gridview 导致 ModalPopUpExtender 关闭

c# - ScintillaNET 未显示方法 block 的折叠

vb.net - 动态代码执行 : String -> Runtime code VB.net

vb.net - Lambda OrderBy方法

c# - 什么是NullReferenceException,如何解决?

vb.net 使用泛型扩展一个类