Have you ever seen design with reasonable usage of protected internal access modifier?

前端 未结 6 813
野的像风
野的像风 2021-02-13 04:01

I haven\'t, but I don\'t say there isn\'t one.

All of the C# developers who read this probably do know what is protected internal and when to use it. My question is simp

6条回答
  •  渐次进展
    2021-02-13 04:56

    Yes, in an inheritance situation whenever a virtual or abstract class member was allowed to be directly accessed by other classes inside the same assembly (internal) in a "friendly"/trusted manner, but also that member could be overriden by derived classes in external assemblies (via protected).

    This combo modifier allows the assembly to fully trust its own contents and internal usage (which is not abnormal), while exposing some of those members to the normal inheritance derivation model for other assemblies.

    No single modifier can do this.

    Or consider the reverse situations:

    • if you only use protected then other classes inside the same assembly cannot access that member.

    • if you only use internal then derived classes (in other assemblies) cannot override that method.

    Assembly1.dll

    // ------ Assembly file 1 .dll --------
    
    // Allow my friends (internal) and derived classes (protected) to do this. 
    public class A {
        internal protected virtual void YoBusiness() {
            //do something
        }
    }
    
    
    class B { // not a derived class - just composites an instance of A
        public B() {
            A a = new A();
            a.YoBusiness(); // Thanks friend for the access! 
        }
    }
    

    Assembly2.dll

    // ------ Assembly file 2 .dll --------
    
    class C : A {  // derived across assemblies
        protected override void YoBusiness() {
            // Hey thanks other guy, I can provide a new implementation. 
        }
    }
    

提交回复
热议问题