我有一个Utility模块,因为VB.NET没有像C#这样的静态类,而Module是VB.NET中的静态类.我使用模块的原因是因为我使用的是Extension方法,它只能在Module中使用.
我不能引用这个模块,但如果我把我的代码放在一个类中.我可以毫无问题地参考它.可能是什么原因?我错过了C#.
编辑:模块位于类库调用Utility中.
我不能引用这个模块,但如果我把我的代码放在一个类中.我可以毫无问题地参考它.有谁知道为什么?
因为VB中的模块不是类,不能用于实例化对象.相反,它们与命名空间类似,不同之处在于命名空间不能直接包含函数.因此,模块的原因是提供一种逻辑分组不属于类的函数的方法.
当你认为并非逻辑上属于一个类时,这很有意义.考虑System.Math.除了奇怪的OOP纯粹主义之外,绝对没有理由把它变成一个类.
顺便说一下,你不能在C#中引用静态类,至少如果我没有正确理解你的"引用"是什么意思的话.也许你可以澄清一下.
.NET编译器可以采用任何类型的语言语法并将其转换为.NET等价物.有时在其他时间没有一对一的通信.
通过使用.NET Reflector,您可以看到编译器实际上在做什么.
在VB.NET中,该模块的存在是因为继承自Visual BASIC和部分来自Microsoft BASIC的遗产.
VB.NET编译器将采用这个
Public Module CoreModule
Dim R As New System.Random(CInt(Microsoft.VisualBasic.Timer))
Public Function D(ByVal Roll As Integer) As Integer
Return R.Next(0, Roll) + 1
End Function
Public Function _1D6() As Integer
Return D(6)
End Function
Public Function _2D6() As Integer
Return D(6) + D(6)
End Function
Public Function _3D6() As Integer
Return D(6) + D(6) + D(6)
End Function
Public Function _4D6() As Integer
Return D(6) + D(6) + D(6) + D(6)
End Function
Public Function CRLF() As String
Return Microsoft.VisualBasic.ControlChars.CrLf
End Function
End Module
Run Code Online (Sandbox Code Playgroud)
把它变成这个(代码遗漏了简洁)
Public NotInheritable Class CoreModule
' Methods
Shared Sub New()
Public Shared Function _1D6() As Integer
Public Shared Function _2D6() As Integer
Public Shared Function _3D6() As Integer
Public Shared Function _4D6() As Integer
Public Shared Function CRLF() As String
Public Shared Function D(ByVal Roll As Integer) As Integer
' Fields
Private Shared R As Random
End Class
Run Code Online (Sandbox Code Playgroud)
在C#中,等同于此
public sealed class CoreModule
{
// Fields
private static Random R;
// Methods
static CoreModule();
public static int _1D6();
public static int _2D6();
public static int _3D6();
public static int _4D6();
public static string CRLF();
public static int D(int Roll);
}
Run Code Online (Sandbox Code Playgroud)
重要的是发出的CIL正确地完成了工作.
这种能力是为什么这么多老的Visual BASIC 6程序员对MS语言变化非常恼火的主要原因.例如,关键字Integer发出Int32而不是Int16.
只要模块被声明为公共模块,模块就会暴露给引用原始程序集的其他程序集.