如何防止某些方法的继承? [英] How to prevent inheritance for some methods?

查看:86
本文介绍了如何防止某些方法的继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止派生类中某些方法或属性的继承?

How can I prevent inheritance of some methods or properties in derived classes?!


public class BaseClass : Collection   
{  
    //Some operations...  
    //Should not let derived classes inherit 'Add' method.  
}

public class DerivedClass : BaseClass      
{        
    public void DoSomething(int Item)      
    {      
        this.Add(Item); // Error: No such method should exist...      
    }      
}  


推荐答案

你想要的模式是组合(Has-a),而不是继承(Is-a)。 BaseClass应该包含集合,而不是从集合继承。 BaseClass然后可以选择性地选择在其接口上公开的方法或属性。

The pattern you want is composition ("Has-a"), not inheritance ("Is-a"). BaseClass should contain a collection, not inherit from collection. BaseClass can then selectively choose what methods or properties to expose on its interface. Most of those may just be passthroughs that call the equivalent methods on the internal collection.

在子类中标记私有事物将不起作用,因为任何具有基本类型的对象变量( Collection x = new DerivedClass())仍然能够通过基本类型访问隐藏成员。

Marking things private in the child classes won't work, because anyone with a base type variable (Collection x = new DerivedClass()) will still be able to access the "hidden" members through the base type.

如果Is-a和Has-a没有为您点击,请根据家长和朋友来考虑。您不能选择您的父母,也无法将其从您的DNA中移除,但您可以选择关联的对象。

If "Is-a" vs "Has-a" doesn't click for you, think of it in terms of parents vs friends. You can't choose your parents and can't remove them from your DNA, but you can choose who you associate with.

这篇关于如何防止某些方法的继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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