本文介绍了如何隐藏在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();
    }
}

我如何prevent从类B继承任何类无法看到该方法 A.MethodToHide()?在C ++中,这是通过使用声明很容易,如 B类:私人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的包装,它隐藏的方法,我们不'T希望暴露给我们组开发,所以我们可以有我们开发的应用程序,新的开发人员可以轻松跟随千篇一律的方式。所以,是的,我相信是一个测试是适用于整个链(WidgetRepository是-A BaseRepository是-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.

推荐答案

您不能做到这一点,preserve的层次结构。如果可能的话,你应该创建定义你的理想接口,则继承的基础类和实现的接口。只引用接口(不包括基类的类型)在code。

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#(删除)基类的方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!