Prevent Exposure of Base Classes (Abstract Classes)

旧城冷巷雨未停 提交于 2019-12-08 09:01:23

问题


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

  • Inconsistent accessibility with abstract classes
  • Inconsistent accessibility
  • Inconsistent accessibility
  • Inconsistent accessibility problem [duplicate]
  • Inconsistent accessibility, property type

回答1:


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.



来源:https://stackoverflow.com/questions/52842532/prevent-exposure-of-base-classes-abstract-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!