C#私有(隐藏)基类 [英] C# private (hidden) base class

查看:132
本文介绍了C#私有(隐藏)基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使C#基类仅在其编译到的库程序集中可访问,同时使从其继承的其他子类公开?

Is it possible to make a C# base class accessible only within the library assembly it's compiled into, while making other subclasses that inherit from it public?

例如:

using System.IO;

class BaseOutput: Stream           // Hidden base class
{
    protected BaseOutput(Stream o)
    { ... }

    ...lots of common methods...
}

public class MyOutput: BaseOutput  // Public subclass
{
    public BaseOutput(Stream o):
        base(o)
    { ... }

    public override int Write(int b)
    { ... }
}

在这里,我希望库的客户端无法访问BaseOutput类,但允许子类MyOutput完全公开.我知道C#不允许基类比子类具有更多的限制性访问,但是还有其他合法的方法可以达到相同的效果吗?

Here I'd like the BaseOutput class to be inaccessible to clients of my library, but allow the subclass MyOutput to be completely public. I know that C# does not allow base classes to have more restrictive access than subclasses, but is there some other legal way of achieving the same effect?

更新

我对此特定库的解决方案是制作基类publicabstract,并使用请勿直接使用此基类" 对其进行文档化.我还创建了基类internal的构造函数,该构造函数有效地防止了外部客户端使用或继承该类.

My solution for this particular library is to make the base class public and abstract, and to document it with "Do not use this base class directly". I also make the constructor of the base class internal, which effectively prevents outside clients from using or inheriting the class.

(很遗憾,因为其他O-O语言让我拥有隐藏的基类.)

(It's a shame, because other O-O languages let me have hidden base classes.)

推荐答案

不幸的是没有.您不能从内部或私有类派生公共类.

Unfortunately not. You can't derive a public class from an internal or private class.

您需要公开基类,或者需要声明所有相似类的所有方法.如果您再次声明所有方法,那么创建一个具有实际实现方式的帮助器类可能会很有用.仍然有很多样板.

You need to either expose the base class, or you need to declare all the methods for all of your similar classes. If you go the route where you declare all methods again, it's probably useful to create a helper class, which has the actual implementation of them. Still it's quite a bit of boilerplate.

这篇关于C#私有(隐藏)基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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