简体   繁体   中英

How to access a static class in same namespace but another assembly?

I am working with a WPF application in C#. I have a number of constants defined in a static class as the following:

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:

int x = Constants.MY_CONSTANT;

Now I add another project to the same solution, and use the same root namespace:

Project 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. 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).

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; 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. Do you need a graphic to illustrate how?

Here's an MSDN link 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

The other answer is close, but it's actually the reverse: Project 2 needs a reference to project 1. The code should then compile.

EDIT:

Sorry, I see that you've already considered this. Yes, someone commented to avoid a circular dependency issue by introducing a third assembly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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