简体   繁体   中英

Public instance of private class - never allowable in c#

Apparently this works in Java:

class BigClass
{
    public SecretClass not_so_secret = new SecretClass();

    public class SecretClass
    {
        // Methods and stuff
    }
}

But is there no equivalent in c#? Where I can create an instance of BigClass but NOT be allowed to create the subclass SecretClass :

class testing_class
{
    BigClass BIG_CLASS_SHOULD_BE_ALLOWED = new BigClass();
    BigClass.SecretClass SUB_CLASS_SHOULD_NOT = new BigClass.SecretClass();
}

I've tried combinations of internal (which sounded right...), private, protected - basically just all of them now :D

Is it a fundamental no-way-round principle in c# to always have this one-way street for access modifiers?

By the way I did find a sort-of answer here referring to Kotlin (whatever that is) and it seems to be a strict thing that just wouldn't make sense to some or be dangerous for some reason - public instances of an "internally" created private class

Is there no way to achieve that level of access in c#?

If you want to make a member (field, property, method, event, delegate or nested type) public, all the types exposed by this member must be public.

However, there is a trick on how you can make the class only instantiateable within BigClass : Make the class abstract , and if you need to write a constructor, make it protected or, since C# 7.2 private protected (see below). Then derive a nested private class from it.

public class BigClass
{
    public SecretClass not_so_secret = new VerySecretClass();

    public abstract class SecretClass
    {
    }

    private class VerySecretClass : SecretClass
    {
    }
}

Also make everything private or protected that you don't need to expose. You can even give the setters more restrictive access modifiers.

public string Text { get; private set; } // or: protected set;

It also helps to make things internal if you are writing a class library. It makes things invisible for other assemblies.


Since C# 7.2 there is also a new level of accessibility (from C# 7 Series, Part 5: Private Protected ):

Private Protected

Private Protected: The member declared with this accessibility can be visible within the types derived from this containing type within the containing assembly. It is not visible to any types not derived from the containing type, or outside of the containing assembly. ie, the access is limited to derived types within the containing 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