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

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

问题描述

喜结果
我怎么能防止在派生类中的一些方法或属性继承?

  
公共类BaseClass的:收集
{
//一些操作...
//不应该让派生类继承'添加'的方法。
}

公共类DerivedClass:BaseClass的
{
公共无效DoSomething的(INT项目)
{
this.Add(项目); //错误:没有这样的方法应该存在...
}
}


解决方案

你想要的图案组成(HAS-A),而不是继承(是一个)。 BaseClass的应该包含集合,而不是从集合继承。然后BaseClass的可以有选择性地选择什么样的方法或属性,将其接口上暴露。多数那些可能只是呼吁内部集合的等效方法快速导入。



标记东西,在子类都不行私人,因为任何一个基本类型变量(集合X =新DerivedClass())仍然能够通过基本类型来访问隐藏的成员。



如果是一个与有,一个不点击你,在父母VS朋友的角度来考虑它。你不能选择你的父母,不能从你的DNA删除它们,但你可以选择你用关联谁。


Hi
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...      
    }      
}  

解决方案

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.

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.

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