防止暴露基类(抽象类) [英] Prevent Exposure of Base Classes (Abstract Classes)

查看:97
本文介绍了防止暴露基类(抽象类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我浏览了许多相关问题,但似乎所有问题都不适合。至少不是以我目前的理解。因为这是一个简单的问题,所以我将简化我的问题和代码。

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.

我有五个课程:

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) { }
}

这里存在一个明显的可访问性问题,在 public 方法中使用了参数 C 。我需要访问类 D 而不暴露类 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.


  • 我应该创建一个类 F 具有 D 的私有实例作为一种包装来防止暴露?

  • 什么是使用抽象的充分理由,因为我不认为这段代码是一个很好的例子。

  • 还有其他方法吗我可以公开 D 而无需公开 A B C

  • 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?

  • 我正在尝试对当前的变化进行手术。

  • 最初,所有课程都是私人课程。

我看过很多相关的文章(以下是其中的一些内容):

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

推荐答案

您可以使用界面隐藏细节。考虑以下内容:

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();
    }
}

示例用法:

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.

这篇关于防止暴露基类(抽象类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆