如何不继承基类中的某些函数到派生类. [英] how to don't inherite some function in base class to derived class.

查看:62
本文介绍了如何不继承基类中的某些函数到派生类.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;

public class Base
{
    public Base()
    {
    }

    void M1()
    {
    }

    void M2()
    {
    }  
}

public class Derived : Base
{
    //this class should get only method m1
}


要求是:基类包含2种方法M1,M2
派生类应仅继承M1,而不继承M2.
为此,我应该在基类中进行哪些更改?

该怎么办呢?

问候,
席达什瓦尔·杜哈尔

已添加代码块&添加了C#标记[/Edit]


The requirement is : the base class contains the 2 methods M1, M2
The derived class should be inherit only M1 and not M2.
For this what should I change in my Base class?

How can this be done?

Regards,
Siddheshwar Duchal

Code block added & C# tag added[/Edit]

推荐答案

如果您像在代码块中那样进行操作,则不会派生M1M2,因为它们是private.保持M2私有,但将M1公开:
If you do it like in your code block, then M1 and M2 will not be derived, because they are private. Keep M2 private, but make M1 public:
using System;
 
public class Base
{
    public Base()
    {
    }
    public void M1()
    {
    }
    void M2()
    {
    }  
}
 
public class Derived : Base
{
    //now this class get only method m1
}



希望对您有所帮助.



Hope this helps.


将M2设为私有

http://msdn.microsoft.com/en-us/library/wxh6fsc7 (v = vs.71).aspx [ http://msdn.microsoft.com/en-us/library/ms173121.aspx [ ^ ]
Make M2 as private

http://msdn.microsoft.com/en-us/library/wxh6fsc7(v=vs.71).aspx[^]
http://msdn.microsoft.com/en-us/library/ms173121.aspx[^]


在继承方法时,您无法更改其可见性-即使您创建了一个新的私有方法来隐藏"它,基本方法仍然可用.
但是,可以防止它被轻易看到:
You can''t change the visibility of methods when you inherit them - even if you create a new private method to "hide" it, the base method will still be available.
However, you can prevent it being seen easily:
public class C1
    {
    public void M1() { Console.WriteLine("C1:M1"); }
    public void M2() { Console.WriteLine("C1:M2"); }
    }
public class C2 : C1
    {
    [Browsable(false),
    EditorBrowsable(EditorBrowsableState.Never)]
    public new void M1() { Console.WriteLine("C2:M1"); }
    }


这会将其从智能感知中隐藏起来,因此两个版本(C1或C2)都不可见-只能从程序集外部看到.仍然可以通过键入名称直接调用C2版本,但是您将无法通过C2变量访问C1版本.
IE.如果在其他解决方案中添加对控件库的引用,则Intellisense不会列出该属性. (但是,如果您输入完整的名称,您仍然可以访问它.很烦人,但是真的.)


This will hide it from intellisense so neither version (C1 or C2) is visible - but only from outside the assembly. It will still be possible to call the C2 version directly by typing in the name, but you won''t be able to access the C1 version via a C2 variable.
I.e. If you add a reference to your control library within an different solution, Intellisense will not list the property. (You can however still access it if you type the name in fully. Irritating, but true.)


这篇关于如何不继承基类中的某些函数到派生类.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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