简体   繁体   English

VS C#与VB中的可变范围

[英]Variable Scope in VS C# vs VB

I have a solution with 2 projects - 1 VB, 1 C#. 我有2个项目的解决方案-1个VB,1个C#。 I want to see and edit a global variable of my VB project from my C# project. 我想从我的C#项目中查看和编辑VB项目的全局变量。 I have declared the string variable (in VB) as Public Shared. 我已经将字符串变量(在VB中)声明为“公共共享”。

I can't see it from my C# project. 我在C#项目中看不到它。

I am not familiar with C#, so I am not sure how to do the equivalent of an 'Imports' statement to get visibility of my VB project and its global variable. 我对C#不熟悉,因此不确定如何执行“导入”语句的等效方法来获得VB项目及其全局变量的可见性。 Can I do this? 我可以这样做吗? Or am I not really thinking this through correctly? 还是我没有真正考虑正确? (I am a VB guy, so C# is a bit of a mystery still). (我是VB专家,所以C#还是个谜)。 Thanks. 谢谢。

Neither VB nor C# supports global variables. VB和C#都不支持全局变量。

You need to add a reference to the VB project from the C# project so that it can use its members. 您需要从C#项目添加对VB项目的引用,以便它可以使用其成员。
You can then access the static field / property of the class / module that you declared it in: 然后,您可以访问在以下位置声明的类/模块的静态字段/属性:

ClassName.PropertyName

While VB supports module-level declares, C# does not. 尽管VB支持模块级声明,但C#不支持。 In C#, a VB module would appear as a static class. 在C#中,VB模块将显示为静态类。 In VB you can also import entire classes and use their shared/static members globally. 在VB中,您也可以导入整个类并在全局范围内使用它们的共享/静态成员。 This is also not something that can be achieved in C#. 这也是用C#不能实现的。

If, in VB, you have: 如果在VB中您具有:

Public Module MyDeclares

    Public MyGlobalString As String

End Module

Then in C#, you would add a reference to that project, and then code like this: 然后在C#中,您将添加对该项目的引用,然后添加如下代码:

using MyProject;

and access the field: 并访问该字段:

MyDeclares.MyGlobalString = "Some text";

EDITED If you want to access properties and methods in another assembly that are declared internal (friend in VB) then you would modify your AssemblyInfo.vb (or AssemblyInfo.cs) file and add an InternalsVisibleTo declaration to the assembly that you want to expose, referencing the assembly (not the namespace) that you want to allow access for. 已编辑如果您要访问声明为内部(在VB中为好友)的另一个程序集中的属性和方法,则可以修改AssemblyInfo.vb(或AssemblyInfo.cs)文件,并向要公开的程序集添加InternalsVisibleTo声明,引用要允许其访问的程序集(而不是名称空间)。

If your assembly uses strong key signing you will have to include the public key in the definition. 如果程序集使用强键签名,则必须在定义中包括公钥。 Follow the link for more information including examples. 单击链接以获取更多信息,包括示例。

我最终将我的模块留在了VB项目中,那是我可以在各个部分中获得良好可见性的唯一方法。

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

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