简体   繁体   English

C#中的全局“模块”类似于VB.NET的模块

[英]Global “Module” in C# similar to VB.NET's Module

I've been searching around here and elsewhere for an answer to this, but I haven't found an exact answer. 我一直在这里和其他地方寻找答案,但我没有找到确切的答案。

I'm fairly new to C#. 我对C#很新。 In VB.NET, you can define a Module, like a class, which has some limitations and also some benefits. 在VB.NET中,您可以定义一个模块,就像一个类,它有一些限制和一些好处。 One of its great benefits is that you can access all of its members globally if you've imported the namespace (ie "using" in c#). 它的一大好处是,如果您已导入命名空间(即在c#中使用“),则可以全局访问其所有成员。 For example: 例如:

Private Sub Test()
    MsgBox(Now)
End Sub

In the method above, MsgBox is a method in the Microsoft.VisualBasic.Interaction module and Now is a property in the Microsoft.VisualBasic.DateAndTime module. 在上面的方法中,MsgBox是Microsoft.VisualBasic.Interaction模块中的方法,而Now是Microsoft.VisualBasic.DateAndTime模块中的属性。 I don't have to qualify the call to either of them in order to use them, although I could: 虽然我可以:我没有必要限制他们中的任何一个使用它们。

Private Sub Test()
    Microsoft.VisualBasic.Interaction.MsgBox(Microsoft.VisualBasic.DateAndTime.Now)
End Sub

I use this feature all the time in my own projects by building my own modules with utility methods and properties. 我通过使用实用程序方法和属性构建自己的模块,在我自己的项目中始终使用此功能。 It's very, very useful. 这非常非常有用。 Is there an equivalent in C#? C#中有等价物吗?

A module in VB.NET is the exact equivalent of a static class in C#. VB.NET中的模块与C#中的静态类完全等效。 The only difference is that the VB.NET compiler by default puts your declarations inside the Module in the global namespace. 唯一的区别是VB.NET编译器默认将您的声明放在Module中的全局命名空间中。 This is a practice that the C# team does not favor, for a good reason, you have to use the class name when you reference a member of the static class in the rest of your code. 这是C#团队不喜欢的做法,出于一个很好的理由,当您在其余代码中引用静态类的成员时,必须使用类名。 In other words, you have to use Math.Pi, not just Pi. 换句话说,你必须使用Math.Pi,而不仅仅是Pi。

It doesn't have to be this way, you can put a Module in a Namespace: 它不必是这种方式,您可以将模块放在命名空间中:

Namespace Contoso.Foobar
    Module MyModule
        '' etc..
    End Module
End Namespace

Now it is the same thing. 现在它是一回事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM