Internal abstract class: how to hide usage outside assembly?

后端 未结 7 1067
再見小時候
再見小時候 2020-12-05 01:30

I have a common assembly/project that has an abstract base class, then several derived classes that I want to make public to other assemblies.

I don\'t want the abs

7条回答
  •  执念已碎
    2020-12-05 02:25

    A way to work around this limitation is to use composition instead of inheritance (there are other good reasons to do this too). For example, instead of:

    internal abstract class MyBase
    {
        public virtual void F() {}
        public void G() {}
    }
    
    public class MyClass : MyBase // error; inconsistent accessibility
    {
        public override void F() { base.F(); /* ... */ }
    }
    

    Do this:

    public interface IMyBase
    {
        void F();
    }
    
    internal sealed class MyBase2 : IMyBase
    {
        public void F() {}
        public void G() {}
    }
    
    public sealed class MyClass2 : IMyBase
    {
        private readonly MyBase2 _decorated = new MyBase2();
        public void F() { _decorated.F(); /* ... */ }
        public void G() { _decorated.G(); }
    }
    

    You can omit the IMyBase interface entirely if the public doesn't need to know about it and your internals don't either.

提交回复
热议问题