[英]How to access a static class in same namespace but another assembly?
I am working with a WPF application in C#. 我正在使用C#中的WPF应用程序。 I have a number of constants defined in a static class as the following:
我在静态类中定义了许多常量,如下所示:
Project1: PROJECT1:
namespace MyCompany
{
public static class Constants
{
public static int MY_CONSTANT = 123456;
}
}
Then all I need to do to access my constant anywhere inside Project 1 is: 然后我需要做的就是在Project 1中的任何地方访问我的常量:
int x = Constants.MY_CONSTANT;
Now I add another project to the same solution, and use the same root namespace: 现在我将另一个项目添加到同一个解决方案中,并使用相同的根命名空间:
Project 2 项目2
namespace MyCompany.MyControl
{
class VideoControl
{
int x;
x = Constants.MY_CONSTANT; //<-- doesn't work
x = MyCompany.Constants.MY_CONSTANT; //<-- doesn't work either
}
}
I just can't figure out a way to access my static Constants class from the second assembly. 我只是无法找到从第二个程序集访问我的静态Constants类的方法。 I also can't add a reference to the first assembly, because it leads to circular dependency (the second project assembly is a WPF control used by the first project assembly).
我也无法添加对第一个程序集的引用,因为它导致循环依赖(第二个项目程序集是第一个项目程序集使用的WPF控件)。
Is what I'm trying to do even possible? 我正在努力做甚么可能吗? Currently my workaround is passing all the required constants in constructor, but I'd rather just access them directly.
目前我的解决方法是在构造函数中传递所有必需的常量,但我宁愿直接访问它们。
You can move all of the static constants from project 1 to project 2, therefore, all of the constants are visible to both project 1 and project 2; 您可以将所有静态常量从项目1移动到项目2,因此,项目1和项目2都可以看到所有常量; I recommended that introduce another project (maybe common) which could help to manage all of the stuffs that shared by all of the other projects.
我建议引入另一个项目(可能很常见),它可以帮助管理所有其他项目共享的所有内容。 it's a common infrastructure project.
这是一个共同的基础设施项目。
You have to add a reference in Project 1 to Project 2, then it should work just fine. 你必须在Project 1中添加一个引用到Project 2,然后它应该工作得很好。 Do you need a graphic to illustrate how?
你需要一个图形来说明如何吗?
Here's an MSDN link http://msdn.microsoft.com/en-us/library/wkze6zky.aspx 这是一个MSDN链接http://msdn.microsoft.com/en-us/library/wkze6zky.aspx
And here's an SO answer with pictures> Adding projects to a project in Visual Studio 2010 这里是图片的回答> 在Visual Studio 2010中将项目添加到项目中
The other answer is close, but it's actually the reverse: Project 2 needs a reference to project 1. The code should then compile. 另一个答案很接近,但它实际上是相反的:项目2需要对项目1的引用。然后代码应该编译。
EDIT: 编辑:
Sorry, I see that you've already considered this. 对不起,我知道你已经考虑过了。 Yes, someone commented to avoid a circular dependency issue by introducing a third assembly.
是的,有人评论说通过引入第三个程序集来避免循环依赖问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.