如何在 C# 中隐藏(删除)基类的方法? [英] How to hide (remove) a base class's methods in C#?

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

问题描述

问题的本质是,给定一个这样的类层次结构:

The essence of the problem is, given a class hierarchy like this:

class A
{
    protected void MethodToExpose()
    {}

    protected void MethodToHide(object param)
    {}
}

class B : A
{
    new private void MethodToHide(object param)
    {}

    protected void NewMethodInB()
    {}
}

class C : B
{
    public void DoSomething()
    {
        base.MethodToHide("the parameter"); // This still calls A.MethodToHide()
        base.MethodToExpose(); // This calls A.MethodToExpose(), but that's ok
        base.NewMethodInB();
    }
}

如何防止从类B"继承的任何类看到方法 A.MethodToHide()?在 C++ 中,这很容易通过使用诸如 class B : private A 之类的声明,但这种语法在 C# 中无效.

How can I prevent any classes that inherit from class "B" from seeing the method A.MethodToHide()? In C++, this was easy enough by using a declaration such as class B : private A, but this syntax is not valid in C#.

对于那些感兴趣(或想知道我真正想要做什么)的人,我们正在尝试做的是为 Rhino.Commons.NHRepository 创建一个包装器来隐藏我们不使用的方法不想暴露给我们的开发人员团队,因此我们可以采用千篇一律的方式来开发我们的应用程序,新开发人员可以轻松遵循.所以是的,我相信Is-A"测试对整个链有效(WidgetRepository Is-A BaseRepository Is-A NHRepository).

For those interested (or wondering what I'm really trying to do), what we're trying to do is create a wrapper for for Rhino.Commons.NHRepository that hides the methods we don't want to expose to our group of developers, so we can have a cookie-cutter way of developing our app that new developers can easily follow. So yes, I believe the "Is-A" test is valid for the whole chain (WidgetRepository Is-A BaseRepository Is-A NHRepository).

编辑:为了论证起见,我应该提到类 A 是我们无法控制的 API 类.否则问题会变得容易得多.

Edit: I should have mentioned, for the sake of argument, that class A is an API class outside of our control. Otherwise the problem gets considerably easier.

推荐答案

你不能这样做并保留层次结构.如果可能,您应该创建定义您的理想的接口,然后子类化基类并实现接口.在您的代码中仅引用接口(而不是基类类型).

You can't do it and preserve the hierarchy. If possible, you should create interfaces that define your ideal, then subclass the bases classes and implement the interfaces. reference the interfaces only (not the base class types) in your code.

适配器模式是专门为了解决如何使用框架的问题而创建的当它的 API 与您的需求不完全一致时.

The Adapter pattern was created specifically to solve the problem of how to use a framework when its API doesn't line up exactly with your needs.

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

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