简体   繁体   中英

Prevent Exposure of Base Classes (Abstract Classes)

So I looked through many related questions and none of them seem to fit all the way. At least not in my current understanding. As this is a simple issue, I'm going to be concise with my question and code.

I have five classes:

internal class A
internal abstract class B : A
internal abstract class C : B
public class D : C
public class E {
    public void X(C c) { }
}

There is an obvious accessibility issue here with the parameter C being used in a public method. I need to access class D without exposing class C . I believe this may be due to the nature of the abstract keyword, and my minimal experience with using it.

To date I have never had a known need to create an abstract class, and this is my first time dealing with it on this level. From my understanding, it isn't really necessary in this case to use abstract classes so long as I remember to implement everything properly.


My Questions

  • Should I create a class F that has a private instance of D as a sort of wrapper to prevent exposure?
  • What is a solid reason to use abstract as I don't believe this code is a good example of it.
  • What are other ways I can expose D without exposing A , B , or C ?

Notes

  • I am trying to be surgical with my current changes.
  • Originally all classes were private.

I've looked at many related posts (here are a few of them):

You can use interfaces to hide the details. Consider this:

//This represents the contract, regardless of the underlying object
public interface ISomeObject
{

}

//Class is internal, but implements the interface
internal class A : ISomeObject { }
internal abstract class B : A { }
internal abstract class C : B { }

//Class D is still internal
internal class D : C { }

public class E
{   
    //Method uses interface, which is public     
    public void X(ISomeObject c) { }

    public ISomeObject DoSomething()
    {
        //Create internal class, return it for use (as a contract)
        return new D();
    }
}

Sample usage:

var e = new E();
var result = e.DoSomething();
e.X(result);

This works because from an external point of view, you are dealing with a public contract, not the actual implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM