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

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

问题描述

所以我查看了许多相关问题,但似乎没有一个完全适合.至少在我目前的理解中不是.由于这是一个简单的问题,我将用我的问题和代码来简明扼要.

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 类.我相信这可能是由于 abstract 关键字的性质以及我使用它的经验很少.

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.

迄今为止,我从未有过创建 abstract 类的已知需求,这是我第一次在这个级别上处理它.根据我的理解,在这种情况下没有必要使用 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. 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 的私有实例作为一种包装器来防止暴露吗?
  • 使用 abstract 的充分理由是什么,因为我认为这段代码不是一个很好的例子.
  • 还有哪些方法可以在不暴露 ABC 的情况下暴露 D?莉>
  • 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):

推荐答案

您可以使用接口隐藏细节.考虑一下:

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天全站免登陆