C#'s “protected internal” means “protected” *O

2019-07-16 01:40发布

问题:

This question already has an answer here:

  • How to make a property protected AND internal in C#? 7 answers

I need to declare a member that is both protected AND internal. However, to my complete bafflement, I just discovered the hard way that "protected internal" actually means protected OR internal. Is there any access modifier that means protected AND internal?

回答1:

Though the CLR supports it, in C# there is no way to force a member to be protected AND internal.

Both C# and VB.NET combine access modifiers using a union, rather than intersection.

There is a workaround for this if you absolutely have to have it. It's not clean, but it works. You can create a helper class with an internal property on it, and then add a protected property of that inner class type to your class. The internal property of the protected property will only be accessible on a subclass within the owning assembly.

Example follows. I've used a generic on the chance that you might want multiple protected internal properties of different types. The generic will allow you to use the one inner class regardless of the desired property type.

public class AccessHelper<T>
{
    internal T Value { get; set; }
}

public class AClass
{
    public AClass()
    {
        InternalProperty.Value = "Can't get or set this unless you're a derived class inside this assembly.";
    }

    protected AccessHelper<String> InternalProperty
    {
        get;
        set;
    }
}


回答2:

protected AND internal is not available in C# (or any other high level .NET language afaik). Although it is supported by the CLR and can be achieved in IL.



回答3:

Citing from Equiso's link:

BTW the CLR does have the notion of ProtectedANDInternal, but C# has no syntax to specify it. If you look at the CLR’s System.Reflection.MethodAttributes enum you’ll see both FamANDAssem as well as FamORAssem (“Family” is the CLR’s term for C#’s protected and “Assem” is C#’s internal).



回答4:

You can't define protected AND internal members in C#, although it is supported by the CLR (MemberAttributes.FamilyAndAssembly)



回答5:

How about internal class and protected member.