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

2019-07-16 01:41发布

This question already has an answer here:

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?

5条回答
做个烂人
2楼-- · 2019-07-16 02:28

How about internal class and protected member.

查看更多
等我变得足够好
3楼-- · 2019-07-16 02:29

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;
    }
}
查看更多
smile是对你的礼貌
4楼-- · 2019-07-16 02:39

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

查看更多
男人必须洒脱
5楼-- · 2019-07-16 02:44

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.

查看更多
做自己的国王
6楼-- · 2019-07-16 02:47

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

查看更多
登录 后发表回答