简体   繁体   English

防止暴露基类(抽象类)

[英]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. public方法中使用参数C ,存在一个明显的可访问性问题。 I need to access class D without exposing class C . 我需要访问D类而不暴露C类。 I believe this may be due to the nature of the abstract keyword, and my minimal experience with using it. 我相信这可能是由于abstract关键字的性质以及我使用它的最少经验所致。

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. 到目前为止,我从来没有必要创建abstract类,这是我第一次在此级别上处理它。 From my understanding, it isn't really necessary in this case to use abstract classes so long as I remember to implement everything properly. 根据我的理解,在这种情况下,只要我记得正确地实现了所有内容,就不必使用abstract类。


My Questions 我的问题

  • Should I create a class F that has a private instance of D as a sort of wrapper to prevent exposure? 我是否应该创建一个具有D的私有实例的类F ,作为一种包装来防止暴露?
  • What is a solid reason to use abstract as I don't believe this code is a good example of it. 使用abstract的坚实理由是什么,因为我不认为这段代码是一个很好的例子。
  • What are other ways I can expose D without exposing A , B , or C ? 在不暴露ABC情况下可以暴露D其他方法有哪些?

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. 之所以可行,是因为从外部角度来看,您正在处理的是公共合同,而不是实际的实施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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