Why can't my public class extend an internal class?

前端 未结 5 1614
猫巷女王i
猫巷女王i 2020-12-01 07:16

I really don\'t get it.

If the base class is abstract and only intended to be used to provide common functionality to public subclasses defined in the assembly, why

5条回答
  •  暖寄归人
    2020-12-01 08:00

    By inheriting from a class, you expose the functionality of the base class through your child.

    Since the child class has higher visibility than its parent, you would be exposing members that would otherwise be protected.

    You can't violate the protection level of the parent class by implementing a child with higher visibility.

    If the base class is really meant to be used by public child classes, then you need to make the parent public as well.

    The other option is to keep your "parent" internal, make it non-abstract, and use it to compose your child classes, and use an Interface to force classes to implement the functionality:

    public interface ISomething
    {
        void HelloWorld();
    }
    
    internal class OldParent : ISomething
    {
        public void HelloWorld(){ Console.WriteLine("Hello World!"); }
    }
    
    public class OldChild : ISomething
    {
        OldParent _oldParent = new OldParent();
    
        public void HelloWorld() { _oldParent.HelloWorld(); }
    }
    

提交回复
热议问题