[英]How can I access to an internal static class from another assembly?
I've the following situation: 我有以下情况:
1) I have an internal static class where my software initialize a form 2) I would like to get the instance of this form to use for other reasons. 1)我有一个内部静态类,我的软件初始化一个表单2)我想得到这个表单的实例用于其他原因。
Example of code: 代码示例:
Class1: 1类:
namespace x {
internal static class Program {
private static Form mainx;
private static void Main() {
.....
.....
mainx=new Form(.....);
Application.run(mainx);
}
}
}
Class2: I want to use one thing like this: Class2:我想用这样的东西:
Form1 try=Program.mainx;
How can i do it? 我该怎么做?
If both assemblies are signed, you can use the InternalsVisibleToAttribute to expose internal members of an assembly to another. 如果两个程序集都已签名,则可以使用InternalsVisibleToAttribute将程序集的内部成员公开给另一个程序集。
I often use this to enable unit testing of internal classes without having to expose them as public. 我经常使用它来启用内部类的单元测试,而不必将它们公开。
You could mark the assembly with the internal class as a friend assembly on the other assembly, with the attribute InternalsVisibleTo . 您可以使用内部类将程序集标记为另一个程序集上的友元程序集,其属性为InternalsVisibleTo 。 You will find more informations about this on the MSDN .
您将在MSDN上找到有关此内容的更多信息。
You need to add this line to your AssemblyInfo
class (in the Properties
folder), ie on the last line. 您需要将此行添加到
AssemblyInfo
类(在“ Properties
文件夹中),即在最后一行。 This must be added in the project where you have declared the internal class. 必须在已声明内部类的项目中添加此项。
[assembly:InternalsVisibleTo("NameOfOtherAssembly")]
If you with to retrieve the mainx
property of your Program
class, you need to make a visible (public or internal) getter on your class: 如果您要检索
Program
类的mainx
属性,则需要在类上创建一个可见的(公共或内部)getter:
internal static class Program
{
private static Form mainx;
...
public static Form GetForm()
{
return mainx;
}
}
In your second class, you should then be able to get the form by calling GetForm()
: 在第二堂课中,您应该可以通过调用
GetForm()
来获取表单:
Form1 try=Program.GetForm();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.