Pregunta

I am working on a class Library and I'm having troubles with accessibility. My class library contains several internal classes which shouldn't be accessed from other applications. Instead I want to create a Singleton Main Class that contains Instances of all the internal classes, so other applications can access the Main class and then use the internal classes from that instance. The picture below explains the hierarchy.

enter image description here

I've tried making the Main Class public and the Internal Classes internal, however this gives me the error Error "Inconsistent accessibility". My Main Class looks like this:

public class Main
{
    private static Main Instance;
    public static Main GetInstance()
    {
        if (Instance == null)
            Instance = new Main();
        return Instance;
    }

    public Debugging Debugger = new Debugging();
}

And one of my Internal Classes (Debugging) looks like this:

internal class Debugging
{
    Content....
}

So I'm hoping that someone can help me to figure out how to make the Internal Classes only accessible through my singleton Main Class.

¿Fue útil?

Solución

I'm not positive from your question what your intent is so I'll break it into two options:

You want `Debugging` accessible to external assemblies, but only via `Main`

There are a few ways how to do this, but the simplest right now for you would be to keep Debugging public, but define only internal constructors. This will allow its usage but external assemblies won't be able to instantiate them, thus forcing them to access the instance created on Main

public class Debugging
{
    internal Debugging() { }
}

You don't want `Debugging` accessible to external assemblies, and but still accessible within your class assembly via `Main`

Simply update the accessibility modifier for Main.Debugger to be internal

internal Debugging Debugger = new Debugging();

Otros consejos

You have to set all of you class public if you have some public access to them (via the Main class).

Otherwise you can set the internal class as internal and provide a set of properties in the Main class (that wrap internal classes' fields/methods) in order to access their field/methods. You can set the constructors of internal class as internal in order to avoid those class instantiations.

In general: Every field/method exposed from a public class should have a public return type.

Some MSDN reference

If you need to access the Debugger class outside the Library you need to change the access modeifier to public. As suggested make the constructor as internal so no one outside the assembly can create an instance of those classes.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top